简体   繁体   中英

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. 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.

I tried using PIL filter FIND_EDGES but it gives very thin edges for an outline.

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. Setting a negative value eg. -1 , will fill in the contour while increasing the parameter will give you a thicker outline.

In this example, we find the contours of each blob using cv2.findContours() then draw the outline onto a mask using cv2.drawContours() . In your case, instead of drawing it onto a mask, you can draw it onto your desired image. With thickness=2 :

在此处输入图像描述

With 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM