用 openCv 填充黑色轮廓
Fill contours in black with openCv
我正在尝试从这张图片中获得全黑 "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
时,我得到以下结果:
我怎样才能得到完整的黑字?
除了我的评论,我还尝试了另一种方式。我用的是灰度图的统计属性
对于这张图片,我使用了图片的均值 select 最佳阈值。
最优值是select通过选择所有低于平均值 33% 的像素值
med = np.mean(gray)
optimal = int(med * 1.33) #selection of the optimal threshold
ret,th = cv2.threshold(gray, optimal, 255, 0)
这是我得到的结果:
现在反转这个图像并获得最大的轮廓,然后你就会得到大 D
编辑:
对于一些直方图比较剧烈的图片,可以使用灰度图的中值代替均值。
我正在尝试从这张图片中获得全黑 "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
时,我得到以下结果:
除了我的评论,我还尝试了另一种方式。我用的是灰度图的统计属性
对于这张图片,我使用了图片的均值 select 最佳阈值。
最优值是select通过选择所有低于平均值 33% 的像素值
med = np.mean(gray)
optimal = int(med * 1.33) #selection of the optimal threshold
ret,th = cv2.threshold(gray, optimal, 255, 0)
这是我得到的结果:
现在反转这个图像并获得最大的轮廓,然后你就会得到大 D
编辑:
对于一些直方图比较剧烈的图片,可以使用灰度图的中值代替均值。