Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply a segmentation mask through OpenCV

I currently have a np.ndarray bitmask in a format where the pixels where the mask is at a value of 1 and the pixels where there is no mask is at a value 0.

I want to "apply" this to another np.ndarray image (3 channels: RGB), where the areas where the mask exists turns slightly more highlighted into the highlighted color. For example, if I want the areas of a human mask to be indicated by the color green, I would want something like what is shown below. I want to know how I can do this with opencv and numpy.

enter image description here

like image 590
SDG Avatar asked Oct 12 '25 04:10

SDG


1 Answers

Let's try cv2.addWeighted:

# sample data
img = np.full((10,10,3), 128, np.uint8)

# sample mask
mask = np.zeros((10,10), np.uint8)
mask[3:6, 3:6] = 1

# color to fill
color = np.array([0,255,0], dtype='uint8')

# equal color where mask, else image
# this would paint your object silhouette entirely with `color`
masked_img = np.where(mask[...,None], color, img)

# use `addWeighted` to blend the two images
# the object will be tinted toward `color`
out = cv2.addWeighted(img, 0.8, masked_img, 0.2,0)

Output:

enter image description here

like image 118
Quang Hoang Avatar answered Oct 14 '25 18:10

Quang Hoang