OpenCV:如何删除不需要的blob或如何将想要的部分复制到空图像中?

时间:2018-03-21 08:44:05

标签: opencv image-processing computer-vision threshold opencv-contour

从下图中,我如何找到结果图像?

enter image description here

此处显示的图像是阈值图像。我尝试过使用形态学操作符,但他们甚至删除了我想要的blob。我怎么能解决这个问题? 任何提示?

以下是我有兴趣获取/找到的结果图片:

enter image description here

import cv2
diff = cv2.imread('Image.png',0)
ret, thresh = cv2.threshold(diff, 12.5, 255, cv2.THRESH_BINARY)
thresh = cv2.dilate(thresh, None, iterations = 1)
cv2.imshow('img', thresh) # This is the  first picture I have shown
cv2.waitKey(0)

2 个答案:

答案 0 :(得分:1)

检测所有斑点,然后按大小,位置或任何你想要的方式对它们进行排序和过滤。

如果您希望有人用勺子为您提供OpenCV手册的内容,可以使用各种教程。

https://www.learnopencv.com/blob-detection-using-opencv-python-c/

https://www.makehardware.com/2016/05/19/blob-detection-with-python-and-opencv/

有很多方法可以删除blob并将其复制到其他图像中。

删除blob的一种简单方法是将其边界框设置为零。

二进制图像也是逻辑运算的理想选择。

https://docs.opencv.org/3.3.1/d0/d86/tutorial_py_image_arithmetics.html

答案 1 :(得分:1)

你大部分都在那里,你现在需要做的就是找到斑点,添加一些轮廓并找到最大的轮廓。简单!下面是C ++中的代码,您可以自行决定如何将其转换为Python:

cv::Mat mat = imread("g0cVU.png");
    Mat origImage = mat;
    Mat canny_output = mat;
    vector<vector<Point> > contours;
    vector<Vec4i> hierarchy;
    cv::Mat greyMat, colorMat;
    cv::cvtColor(mat, greyMat, CV_BGR2GRAY);
    int thresh = 100;
    RNG rng(12345);
    ///// Detect edges using canny
    Canny(greyMat, canny_output, thresh, thresh * 2, 3);
    /// Find contours
    findContours(canny_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
    int largest_area = 0;
    int largest_contour_index = 0;
    Rect bounding_rect;
    /// Draw contours
    Mat drawing = Mat::zeros(canny_output.size(), CV_8UC3);
    for (int i = 0; i< contours.size(); i++)
    {
        Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
        drawContours(drawing, contours, i, color, 2, 8, hierarchy, 0, Point());
        double a=contourArea( contours[i],false);  //  Find the area of contour
       if(a>largest_area){
       largest_area=a;
       largest_contour_index=i;                //Store the index of largest contour
       bounding_rect=boundingRect(contours[i]); // Find the bounding rectangle for biggest contour
       }
    }
    rectangle(origImage, bounding_rect, Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)),2);
    /// Show in a window
    namedWindow("Contours", CV_WINDOW_AUTOSIZE);
    imshow("Contours", drawing);

    cv::namedWindow("img");
    cv::imshow("mat", mat);
    cv::imshow("mat", origImage);
    cv::imshow("mat123", drawing);
    cv::waitKey(0);

结果如下:

original image with contours

Largest contour detected

您可以在底部图像中看到最大的contor周围有一个棕色矩形。

o显然一旦你拥有了最大的blob(或者你认为的任何blob“正确的blob”),你可以将其他所有内容设置为黑色,这是相当简单的。