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

OpenCV: How can I remove unwanted blobs or how can I copy wanted parts into an empty image?

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

这里显示的图像是阈值图像。我试过使用形态学运算符,但它们甚至删除了我想要的斑点。我该如何解决这个问题? 有什么提示吗?

下面是我感兴趣的效果图get/find:

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)

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

如果您想让别人spoon-feed您了解 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 的一种简单方法是将其边界框设为零。

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

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

你已经完成大部分工作了,你现在需要做的就是找到斑点,添加一些轮廓并找到最大的一个。简单!下面是 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);

结果如下:

您可以在底部图片中看到最大的圆锥周围画有一个棕色矩形。

o 显然,一旦您拥有最大的斑点(或您认为 "the correct one" 的任何斑点),您就可以将其他所有内容设置为黑色,这非常简单。