Hands-On Image Processing with Python
上QQ阅读APP看书,第一时间看更新

Image manipulations with numpy array slicing 

The next code block shows how slicing and masking with numpy arrays can be used to create a circular mask on the lena image:

lena = mpimg.imread("../images/lena.jpg") # read the image from disk as a numpy ndarray
print(lena[0, 40])
# [180 76 83]
# print(lena[10:13, 20:23,0:1]) # slicing
lx, ly, _ = lena.shape
X, Y = np.ogrid[0:lx, 0:ly]
mask = (X - lx / 2) ** 2 + (Y - ly / 2) ** 2 > lx * ly / 4
lena[mask,:] = 0 # masks
plt.figure(figsize=(10,10))
plt.imshow(lena), plt.axis('off'), plt.show()

The following figure shows the output of the code: