-
Points on circle
I loaded an image into a 2D array, where each index is a pixel. The image is just a white circle on black background.
I am having trouble locating the upper-most, left-most, right-most and bottom-most pixels of that circle.
Code:
// 255 = white, 0 = black
//left
if (circle[i][j] == 255 && circle[i-1][j] == 0 && circle[i][j-1] == 0)
cout << "left: " << i << "," << j << endl;
//right
if (circle[i][j] == 255 && circle[i-1][j] == 0 && circle[i][j+1] == 0)
cout << "right: " << i << "," << j << endl;
//up
if (circle[i][j] == 255 && circle[i-1][j] == 0 && circle[i][j-1] == 0)
cout << "up: " << i << "," << j << endl;
//down
if (circle[i][j] == 255 && circle[i+1][j] == 0 && circle[i][j-1] == 0)
cout << "down: " << i << "," << j << endl;
This is not working out for me, what would be the proper way to do this ?
-
The first question to ask yourself is "why does my 'left' check check up? and why does my 'right' check check left and down? and why does my 'up' check check left? and why does my down check check right and up?"
Once you've dealt with that, then you can ask yourself "what are i and j? And what happens when i is 0, so that i can't even do i-1?"
-
It's a bit tricky to figure out what the leftmost or whatever pixel of an image is all at once like that. It might be easier if you recorded the leftmost pixel found so far, and update that when you find an even further left pixel. Something like this:
Code:
int leftmost_x = INT_MAX, leftmost_y = -1;
for(int i = 0; i < WIDTH; i ++) {
for(int j = 0; j < HEIGHT; j ++) {
if(circle[i][j] == 255 && i < leftmost_x) {
leftmost_x = i;
leftmost_y = j;
}
}
}
if(leftmost_y >= 0) {
// leftmost pixel found at (leftmost_x, leftmost_y)
}
else {
// no pixels found at all
}