More Efficient Way to Find Nearest Black Pixel?
in
Programming Questions
•
9 months ago
I've been attempting to come up with a way to determine the nearest black pixel to a given coordinate. Initially, I was trying to use pvectors, but I was having trouble sorting them (I'm new to Processing, and programming in general). In the end, I landed on the following:
- PImage img;
- int col; // variable to capture colour of pixels
- int currx = 1; // current value of x coordinate
- int curry = 1; // current value of y coordinate
- int targx; // x coordinate of closest black pixel
- int targy; // y coordinate of closest black pixel
- float targdist; // distance (euclidean) to target
- void setup() {
- img = loadImage("test.png");
- size(img.width, img.height);
- targdist = dist(0,0,img.width,img.height); // set initial target distance to diagonal of image
- for (int y=0; y<img.height; y++) { // loop through all pixels
- for (int x=0; x<img.width; x++) {
- col = img.get(x, y) & 0xFF;
- float z;
- if(col == 0){ // if pixel is black
- z = dist(currx, curry, x, y); // calculate distance between current coord and target
- if(z < targdist) { // if current black pixel closer than previous
- targdist = z; // update target distance and coordinates
- targx = x;
- targy = y;
- }
- }
- }
- }
- }
- void draw() {
- image(img, 0, 0);
- print("(" + targx + ", " + targy + ") is " + targdist + " units away from (" + currx + ", " + curry + ")");
- noLoop();
- }
However, I'm wondering if there's a more efficient way of doing this. For now, this meets my needs, but in the future I may want to extend this to find, say, the closest gray -> black pixel pair for each gray pixel (not sure I worded that well, but for each gray pixel, find the closest black pixel to it). I doubt this method will work well for that. Can anyone point me in the best direction to tackle something like that?
1