套用遮罩
雖然遮罩是二元的,但你可以將它「套用」到影像上,來過濾掉 mask 為 False 的像素。
NumPy 的 where() 函式是套用遮罩的彈性做法。它接受三個引數:
np.where(condition, x, y)
condition、x 和 y 可以是陣列或單一數值。這讓你可以保留原始影像的像素值,同時把被遮罩的位置設為 0。
現在來練習套用遮罩,從手部 X 光影像(im)中選出類似骨頭的像素。
本練習屬於課程
Python 的生醫影像分析
練習說明
- 建立一個布林骨骼遮罩,選取大於或等於 145 的像素。
- 使用
np.where()將遮罩套用到影像上。未被遮罩包含的值應設為0。 - 為套用遮罩後的影像繪製直方圖。使用以下引數只選取非零像素:
min=1、max=255、bins=255。 - 繪製套用遮罩的影像與直方圖。這部分已為你完成。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Import SciPy's "ndimage" module
____
# Screen out non-bone pixels from "im"
mask_bone = ____
im_bone = np.where(____, ____, ____)
# Get the histogram of bone intensities
hist = ____
# Plot masked image and histogram
fig, axes = plt.subplots(2,1)
axes[0].imshow(im_bone)
axes[1].plot(hist)
format_and_render_plot()