Looping through pixels in an image and comparing them to previous/next ones. [closed]
The title says it all.
What I am trying to do is loop through all pixels in an image (successfully so far) and compare one pixel's color to the previous and next one. (Could be next column or next row, doesn't really matter)
Oh ye, and eventually, modify the previous/next pixel.
Now, the idea sounds pretty simple, but since I'm new to OpenCV I must be doing something wrong since I keep getting errors. (More like.. when I run the project it just stops unexpectedly)
My code:
for (int row = 0; row < image.rows; row++)
{
for (int col = 0; col < image.cols; col++)
{
Vec3b pColor = image.at<Vec3b>(Point(col, row));
if (pColor[0] > 240 && pColor[1] > 240 && pColor[2] > 240)
{
if (row > 0 && col > 0 && row < (image.rows - 1) && col < (image.cols - 1))
{
Vec3b nColor = image.at<Vec3b>(Point(col - 1, row));
if (nColor[0] < 240 && nColor[1] < 240 && nColor[2] < 240)
{
image.at<Vec3b>(col - 1, row)[0] = 1;
image.at<Vec3b>(col - 1, row)[1] = 1;
image.at<Vec3b>(col - 1, row)[2] = 255;
}
Of course, there is more, but this is the problematic area. I've found the exact line which causes the sudden stop and it is:
Vec3b nColor = image.at<vec3b>(Point(col - 1, row));
If I remove the "-1" from the line, the code runs, but of course, not as I want it to. Perhaps I am missing some knowledge of how OpenCV works. I mean, this should work by my understanding, I make sure the current row and column is more than 0 which means I have enough place to go back by one in each of them, so I see no problem.
Any help is greatly appreciated.
Thank you in advance.
Vec3b pColor = image.at<Vec3b>(col, row);
if (row > 0 && col > 0 && row < (image.rows - 1) && col < (image.cols - 1))
if you properly set the loop parametersimage
in place seems like a bad idea, specially if you're gonna to compare current and next pixel, because you'll eventually compare original and modified pixel values. All depends on what you gonna achieve but...Point(col - 1, row)
is (-1,0) for col=0,row=0