基于二值图像的图像分割

时间:2017-03-14 19:51:47

标签: c++ opencv image-processing image-segmentation edge

我有这两张图片,图片1 图片2 的二进制文件。

我想以图片1 的形式从图片2 中分割出对象。

           image 1                            image 2

enter image description here enter image description here

我已经查看了几个样本,但没有一个是有用的。考虑将图像2叠加到图像1的白色区域,使用具有条件的copyTo函数,但我确信有更好的方法。如果有人能告诉我方法或C ++代码段来解决这个问题,我真的很感激!

2 个答案:

答案 0 :(得分:3)

是的,你是对的。

如上所述,您可以执行图像屏蔽,而不是在C ++中使用复制

cv::bitwise_and(image1, image2, output);

其中image1是掩码,image2是原始图像。

另一种对我有用的方法是:

image2.copyTo(image1, image1);

其中image1是掩码,image2是原始图像。结果如下所示:

enter image description here

答案 1 :(得分:-2)

您需要使用Otsu阈值将前景与背景分开

/**@file
  Get the Otusu threshold for image segmentation.
  @param[in] gray - the grayscale image
  @param width - image width
  @param height - image height
  @returns Threshold at which to split pixels into foreground and
           background.
  @image html maggie.jpg  Margaret Thatcher (1925-2013) greyscale photograph
  @image html maggieotsu.gif Mrs Thatcher Otsu thresholded
 */
int getOtsuthreshold(unsigned char *grey, int width, int height)
{
  int hist[256] = {0};
  int wB = 0;
  int wF;
  float mB, mF;
  float sum = 0;
  float sumB = 0;
  float varBetween;
  float varMax = 0.0f;
  int answer = 0;
  int i;
  int k;

  for(i=0;i<width*height;i++)
    hist[grey[i]]++;

  /* sum of all (for means) */
  for (k=0 ; k<256 ; k++) 
       sum += k * hist[k];

  for(k=0;k<256;k++)
  {
     wB += hist[k];               
     if (wB == 0) 
         continue;

     wF = width*height - wB;            
     if (wF == 0) 
       break;

     sumB += (float) (k * hist[k]);

     mB = sumB / wB;            /* Mean Background */
     mF = (sum - sumB) / wF;    /* Mean Foreground */

     /* Calculate Between Class Variance */
     varBetween = (float)wB * (float)wF * (mB - mF) * (mB - mF);

     /* Check if new maximum found */
     if (varBetween > varMax) 
     {
       varMax = varBetween;
       answer = k;
     }

  }
  return answer;
}

https://github.com/MalcolmMcLean/binaryimagelibrary

相关问题