Search code examples
imageopencvpixeliplimage

Weird OpenCV Code


This is weird. I have this following code:

int white = 0;
int black = 0;   
for (int i = 0; i < height; i++) {
    for (int j = 0; j < width; j++) {
        int total = 0;
        for (int x = i - 1; x <= i + 1; x++) {
            for (int y = j - 1; y <= j + 1; y++) {
                total += data[x*step + y];
            }
        }
        if (total == (255 * 9)) {
            white += 1;
            // data[i*step + j] = 255;
        }
        else {
            black += 1;
            // data[i*step + j] = 0;
        }
    }
}
cout << white << endl << black << endl;

When I run this code, it will input the white and black correctly. But for some reason, when I uncomment the data, the code will be wrong. Btw, I'm just simply eroding an image, and this is what I've come up so far.


Solution

  • When you uncomment those statements you will then be modifying data[] "in place" and, because you are performing a neighbourhood operation, that modified data will be re-used as input data in subsequent iterations, which will of course make the results invalid. You need a separate output image to write these new values to.