c# - 用openCv将轮廓填充为黑色

标签 c# opencv opencvsharp

我正在尝试从这张图片中获得整个黑暗的“D”:

enter image description here

使用此代码,我得到以下结果:

```

        Cv2.Threshold(im_gray, threshImage, 80, 255, ThresholdTypes.BinaryInv); // Threshold to find contour

        Cv2.FindContours(
            threshImage,
            out contours,
            out hierarchyIndexes,
            mode: RetrievalModes.Tree,
            method: ContourApproximationModes.ApproxSimple
        );

        double largest_area = 0;
        int largest_contour_index = 0;
        Rect rect = new Rect();
        //Search biggest contour
        for (int i = 0; i <contours.Length; i++)
        {
            double area = Cv2.ContourArea(contours[i]);  //  Find the area of contour

            if (area > largest_area)
            {
                largest_area = area;
                largest_contour_index = i;               //Store the index of largest contour
                rect = Cv2.BoundingRect(contours[i]); // Find the bounding rectangle for biggest contour
            }
        }

        Cv2.DrawContours(finalImage, contours, largest_contour_index, new Scalar(0, 0, 0), -1, LineTypes.Link8, hierarchyIndexes, int.MaxValue);

```

但是当我保存finalImage时,我得到以下结果:
enter image description here
我如何获得整个黑字?

最佳答案

除了我的评论外,我还尝试了另一种方法。我使用了灰度图像的统计属性。
对于此图像,我使用图像的平均值值来选择最佳阈值。
通过选择低于平均值33%的所有像素值来选择最佳值

med = np.mean(gray)
optimal = int(med * 1.33) #selection of the optimal threshold

ret,th = cv2.threshold(gray, optimal, 255, 0)
这就是我得到的结果:
enter image description here
现在反转此图像并获得最大轮廓,然后您将获得Big D
编辑:
对于某些带有剧烈直方图的图像,可以使用灰度图像的中值代替表示

关于c# - 用openCv将轮廓填充为黑色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42371882/

相关文章:

c# - 数据库插入帮助?

没有java的android NDK adb可执行文件

opencv - 如何在OpenCvSharp中从InputOutputArray创建对象?

opencv - 如何使用OpenCV逐渐减轻图像的底部边框?

c# - 如何将 HttpPostedFileBase 文件作为另一个项目的方法的参数传递

c# - 将从网络服务接收到的二进制图像数据转换为 byte[]

c# - Xamarin.Android : How to capture Button events defined in the OnClick XML attribute?

c++ - 访问负像素值 OpenCV

c++ - 奇怪的 Adob​​e Alchemy 编译器失败

c# - 无法将 'Emgu.CV.Matrix<double>'类型隐式转换为'double