AMANDEEP KAUR
AMANDEEP KAUR

Reputation: 33

How to superimpose segmentation result over other image

I have the original image and its segmented mask. My task is to get a colored segmentation plot over the original image. I tried following this, but it gives me the same output as the input image.

import skimage.filters.rank
import skimage.morphology
import numpy as np
import cv2

# Load images as greyscale but make main RGB so we can annotate in colour
seg  = cv2.imread('segmented.png',cv2.IMREAD_GRAYSCALE)
main = cv2.imread('main.png',cv2.IMREAD_GRAYSCALE)
main = cv2.cvtColor(main,cv2.COLOR_GRAY2BGR)

# Create structuring element that defines the neighbourhood for morphology
selem = skimage.morphology.disk(1)

# Mask for edges of segment 1 and segment 2
# We are basically looking for pixels with value 1 in the segmented image within a radius of 1 pixel of a black pixel...
# ... then the same again but for pixels with a vaue of 2 in the segmented image within a radius of 1 pixel of a black pixel
seg1 = (skimage.filters.rank.minimum(seg,selem) == 0) & (skimage.filters.rank.maximum(seg, selem) == 1)
seg2 = (skimage.filters.rank.minimum(seg,selem) == 0) & (skimage.filters.rank.maximum(seg, selem) == 2)

main[seg1,:] = np.asarray([0, 0,   255]) # Make segment 1 pixels red in main image
main[seg2,:] = np.asarray([0, 255, 255]) # Make segment 2 pixels yellow in main image

# Save result
cv2.imwrite('result.png',main) 

The original image:

enter image description here

The segmented image:

enter image description here

This is a similar example of the result I want to achieve:

An example

Upvotes: 1

Views: 1898

Answers (1)

spb
spb

Reputation: 175

It can be easily done using matplotlib.pyplot

import matplotlib.pyplot as plt

image = plt.imread('image.png')
mask = plt.imread('mask.png')

fig, ax = plt.subplots()
ax.imshow(image, cmap='gray')
ax.imshow(mask, cmap='gray', alpha=0.5)
fig.show()
fig.savefig('overlapped.png')

You can also change colors by changing colormap parameter, cmap.

Upvotes: 3

Related Questions