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.
CodePudding user response:
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)
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)
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
CodePudding user response: