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.
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.
First let's generate some image we can work on.
import numpy as np
import matplotlib.pyplot as plt
img = np.zeros((250,250), dtype=int)
img += np.arange(-124, 126, 1)**2
img = img.T + np.arange(-124, 126, 1)**2
img += np.arange(1, 251, 1)**2
img = (img/(np.max(img)/4.5)).astype(int)
plt.imshow(img)
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)