0

我试图从这张图片中得到一个完整的黑暗“D”:

在此处输入图像描述

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

```

        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,我得到以下结果: 在此处输入图像描述 我怎样才能得到整个黑色字母?

4

1 回答 1

3

除了我的评论,我尝试了另一种方式。我使用了灰度图像的统计属性。

对于此图像,我使用图像的平均值来选择最佳阈值。

通过选择平均值的 33% 以下的所有像素值来选择最佳值

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

ret,th = cv2.threshold(gray, optimal, 255, 0)

这是我得到的结果:

在此处输入图像描述

现在反转这个图像并获得最大的轮廓,然后你就会得到大 D

编辑:

对于一些直方图剧烈的图像,可以使用灰度图像的中值代替均值

于 2017-02-21T16:40:50.767 回答