How to create an outline (with controllable thickness) from a mask segmentation image in Python?

Viewed 2193

Mask Image

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?

1 Answers

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:

enter image description here

With thickness=5:

enter image description here

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