用于C ++中图像分析的OpenCV二进制图像掩码

时间:2015-07-22 05:00:14

标签: c++ opencv image-processing mask threshold

我试图分析一些图像外部有很多噪点的图像,但是内部有一个形状清晰的圆形中心。中心是我感兴趣的部分,但外部噪音影响了我对图像的二值阈值。

为了忽略噪音,我试图设置一个已知中心位置和半径的圆形遮罩,这个圆圈外的所有像素都变为黑色。我认为圆圈内的所有内容现在都可以通过二进制阈值分析来轻松分析。

我只是想知道是否有人能够指出我正确的方向来解决这类问题吗?我已经看过这个解决方案了:How to black out everything outside a circle in Open CV但是我的一些约束条件有所不同,我对加载源图像的方法感到困惑。

提前谢谢!

2 个答案:

答案 0 :(得分:20)

//First load your source image, here load as gray scale
cv::Mat srcImage = cv::imread("sourceImage.jpg", CV_LOAD_IMAGE_GRAYSCALE);

//Then define your mask image
cv::Mat mask = cv::Mat::zeros(srcImage.size(), srcImage.type());

//Define your destination image
cv::Mat dstImage = cv::Mat::zeros(srcImage.size(), srcImage.type());    

//I assume you want to draw the circle at the center of your image, with a radius of 50
cv::circle(mask, cv::Point(mask.rows/2, mask.cols/2), 50, cv::Scalar(255, 0, 0), -1, 8, 0);

//Now you can copy your source image to destination image with masking
srcImage.copyTo(dstImage, mask);

然后在dstImage上进行进一步处理。假设这是您的源图像:

enter image description here

然后上面的代码将此作为灰度输入:

enter image description here

这是你创建的二元掩码:

enter image description here

这是掩蔽操作后的最终结果:

enter image description here

答案 1 :(得分:4)

由于您正在寻找一个内部有形状的透明圆形中心,您可以使用Hough变换来获得该区域 - 仔细选择参数将有助于您完美地获得该区域。

详细教程如下: http://docs.opencv.org/doc/tutorials/imgproc/imgtrans/hough_circle/hough_circle.html

将区域外的像素设置为黑色:

创建蒙版图像:     cv::Mat mask(img_src.size(),img_src.type());

用白色标记内部的点:

cv::circle( mask, center, radius, cv::Scalar(255,255,255),-1, 8, 0 );

您现在可以使用bitwise_AND,从而获得仅包含掩码中的像素的输出图像。

cv::bitwise_and(mask,img_src,output);