2014-01-29 68 views
0

这很奇怪。我有以下代码:奇怪的OpenCV代码

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; 

当我运行此代码时,它将正确输入白色和黑色。但由于某些原因,当我取消注释数据时,代码将会出错。顺便说一句,我只是简单地削弱了一幅图像,而这正是我迄今为止所提出的。

回答

4

当取消注释那些你会然后“就地”进行修改data[]和,因为要执行邻域操作,即修改的数据将被重新用作随后的迭代中的输入数据,这将陈述当然会导致结果无效。您需要一个单独的输出图像来将这些新值写入。

+0

是我试图做的 - 修改数据。嗯,我试图做到这一点单独的输出图像(克隆图像,并将其分配给不同的IplImage),但仍然,输出是相同的 –

+1

好吧,我终于明白你在说什么。现在代码作品谢谢! –

+1

将'IplImage'结果克隆到头部克隆(需要'cvCreateImage'和'cvCopy'才能正确执行)。 cv :: Mat :: clone()要容易得多。 – William

3

您的代码溢出。

如果你想检查一个3x3的邻域,你需要在所有边上都留出1个像素的边界。

也,你不能这样做就地,你需要第二个垫子的结果。

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; 
+0

嗯感谢您的信息!但这并没有改变任何东西 –