select a few object from a segmented image

Viewed 90

I have a segmented image like the one below where each object has a different pixel value (i.e. instance segmentation. This has been achieved using skimage.measure.label. How can I select specific objects from this image. I would for instance like all objects labelled 11, 12, and 13 to retain their label or be labelled as 1 and everything else to be assigned a pixel value of 0. enter image description here

1 Answers

You can do that with Numpy quite simply:

#!/usr/bin/env python3

import numpy as np
from PIL import Image

im = Image.open('start.png').convert('L')
na = np.array(im)

# Make any pixel less than 11 or greater than 13 become zero
na[(na<11) | (na>13)] = 0
Image.fromarray(na).save('result1.png')

# Reload unmodified image for second method
na  = np.array(im)
# Make any pixel outside range black, any pixel in range white
res = np.where(((na<11) | (na>13)), 0, 255).astype(np.uint8)
Image.fromarray(res).save('result2.png')

Start Image

enter image description here

Result1

enter image description here

Result2

enter image description here

Related