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.
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.
해결책
다른 팁
your code is overflowing.
if you want to check a 3x3 neighbourhood, you need to spare a 1 pixel border at all sides.
also, you can't do it in-place, you need a second Mat for the result.
Mat m2 = m.clone();
int white = 0;
int black = 0;
for (int i = 1; i < height - 1; i++){ // border
for (int j = 1; j < width - 1; j++){ // border
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;
m2.data[i*step + j] = 255; // *write* to a 2nd mat
}
else{
black += 1;
m2.data[i*step + j] = 0; // *write* to a 2nd mat
}
}
}
cout << white << endl << black << endl;
제휴하지 않습니다 StackOverflow