Overlay an image segmentation with numpy and matplotlib Overlay an image segmentation with numpy and matplotlib arrays arrays

Overlay an image segmentation with numpy and matplotlib


Why don't you use imshow instead?

You can plot a 2D image by doing:

plt.imshow(Image1, cmap='gray') # I would add interpolation='none'

Afterwards, you can easily overlay the segmentation by doing:

plt.imshow(Image2_mask, cmap='jet', alpha=0.5) # interpolation='none'

Changing the alpha will change the opacity of the overlay.

Additionaly, why do you create 2 masks? Only one should be enough, you can do:

Image2_mask = ma.masked_array(Image2 > 0, Image2)

Practical example:

import numpy as npmask = np.zeros((10,10))mask[3:-3, 3:-3] = 1 # white square in black backgroundim = mask + np.random.randn(10,10) * 0.01 # random imagemasked = np.ma.masked_where(mask == 0, mask)import matplotlib.pyplot as pltplt.figure()plt.subplot(1,2,1)plt.imshow(im, 'gray', interpolation='none')plt.subplot(1,2,2)plt.imshow(im, 'gray', interpolation='none')plt.imshow(masked, 'jet', interpolation='none', alpha=0.7)plt.show()

enter image description here


I can give you my function two overlap a picture and a mask of dataset :

def get_overlapped_img(filename, img_folder, mask_folder):# Import orginal imgimg = cv2.imread(img_folder+"/"+filename+".jpg")# Import and convert the mask from binary to RGBmask = Image.open(mask_folder+"/"+filename+".png").convert('RGB')width, height = mask.size# Convert the white color (for blobs) to magentamask_colored = change_color(mask, width, height, (255, 255, 255), (186,85,211))# Convert the black (for background) to white --> important to make a good overlappingmask_colored = change_color(mask_colored, width, height, (0, 0, 0), (255,255,255))return cv2.addWeighted(np.array(img),0.4,np.array(mask_colored),0.3,0)

Function to change color of each pixel in a picture :

def change_color(picture, width, height, ex_color, new_color):# Process every pixelfor x in range(width):    for y in range(height):        current_color = picture.getpixel( (x,y) )        if current_color == ex_color:            picture.putpixel( (x,y), new_color)return picture