[英]How to create an outline (with controllable thickness) from a mask segmentation image in Python?
Here I have an image for a segmentation output from one of the segmentation models.在这里,我有一张来自其中一个分割模型的分割图像 output。 I would like to create an outline for these masks and then put that outline on the original image to indicate the predicted areas on the image as segmentation output.
我想为这些掩码创建一个轮廓,然后将该轮廓放在原始图像上,以将图像上的预测区域指示为分割 output。
I tried using PIL filter FIND_EDGES but it gives very thin edges for an outline.我尝试使用 PIL 过滤器 FIND_EDGES,但它为轮廓提供了非常薄的边缘。
Is there any way to convert this mask image into an image with just outlines for these masks where I can control the thickness of the outline?有没有办法将此蒙版图像转换为仅具有这些蒙版轮廓的图像,我可以在其中控制轮廓的厚度?
If I understand correctly, you want to find the outline of all the blobs then draw this outline onto another image with controllable outline thickness.如果我理解正确,您想找到所有斑点的轮廓,然后将此轮廓绘制到另一个具有可控轮廓厚度的图像上。 You can do this using
cv2.drawContours()
and control the outline thickness using the thickness
parameter.您可以使用
cv2.drawContours()
执行此操作,并使用thickness
参数控制轮廓厚度。 Setting a negative value eg.设置负值,例如。
-1
, will fill in the contour while increasing the parameter will give you a thicker outline. -1
,将填充轮廓,同时增加参数会给你一个更厚的轮廓。
In this example, we find the contours of each blob using cv2.findContours()
then draw the outline onto a mask using cv2.drawContours()
.在此示例中,我们使用 cv2.findContours() 找到每个 blob 的轮廓,然后使用
cv2.drawContours()
cv2.findContours()
将轮廓绘制到蒙版上。 In your case, instead of drawing it onto a mask, you can draw it onto your desired image.在您的情况下,您可以将其绘制到所需的图像上,而不是将其绘制到蒙版上。 With
thickness=2
: thickness=2
:
With thickness=5
: thickness=5
:
import cv2
import numpy as np
image = cv2.imread('1.png')
mask = np.ones(image.shape, dtype=np.uint8) * 255
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cnts = cv2.findContours(gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
cv2.drawContours(mask, [c], -1, (36, 255, 12), thickness=5)
cv2.imshow('mask', mask)
cv2.waitKey()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.