Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extract specific region in the image

I have an image in which I am interested in a specific region in the image.. for example I want to extract region 5-same pixel value everywhere (and background 0). Meaning region 3 and 4 should not be present in the output image(should be 0). Here is the image looks like.

enter image description here

I can do it with a for loop but since the image is large it takes time.. because I have a 3D stack. Any simpler approach would be appreciated.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

First let’s generate some image we can work on.

import numpy as np
import matplotlib.pyplot as plt 

img = np.zeros((50,50), dtype=int)
img += np.arange(-24, 26, 1)**2
img = img.T + np.arange(-24, 26, 1)**2
img += np.arange(1, 51, 1)**2

img = (img/(np.max(img)/4.5)).astype(int)

plt.imshow(img)

Example image

Now we can mask it using np.where:

bg_value = 0 # Background value
want_value = 2 # Value that we are interested in

masked = np.where(img==want_value, img, bg_value)

plt.imshow(masked)

Masked image

Note that the color-scale changed between the images, the original pixel value is still in the masked array:

print(np.max(img))
# 4
print(np.max(masked))
# 2
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading