使用NumPy(或SciPy)裁剪部分图像

2024-04-19 15:46:57 发布

您现在位置:Python中文网/ 问答频道 /正文

使用numpyscipy(我没有使用OpenCV)尝试从图像中裁剪区域。

例如,我有这个:

enter image description here

我想得到这个:

enter image description here

有没有类似cropPolygon(image, vertices=[(1,2),(3,4)...])numpySciPy的东西?


Tags: 图像imagenumpy区域scipyopencvverticescroppolygon
1条回答
网友
1楼 · 发布于 2024-04-19 15:46:57

你在用matplotlib吗?

我以前采用的一种方法是使用matplotlib.path.Path.contains_points()方法构造一个布尔掩码,然后可以使用该掩码索引到图像数组中。

例如:

import numpy as np
from matplotlib.path import Path
from scipy.misc import lena

img = lena()

# vertices of the cropping polygon
xc = np.array([219.5, 284.8, 340.8, 363.5, 342.2, 308.8, 236.8, 214.2])
yc = np.array([284.8, 220.8, 203.5, 252.8, 328.8, 386.2, 382.2, 328.8])
xycrop = np.vstack((xc, yc)).T

# xy coordinates for each pixel in the image
nr, nc = img.shape
ygrid, xgrid = np.mgrid[:nr, :nc]
xypix = np.vstack((xgrid.ravel(), ygrid.ravel())).T

# construct a Path from the vertices
pth = Path(xycrop, closed=False)

# test which pixels fall within the path
mask = pth.contains_points(xypix)

# reshape to the same size as the image
mask = mask.reshape(img.shape)

# create a masked array
masked = np.ma.masked_array(img, ~mask)

# if you want to get rid of the blank space above and below the cropped
# region, use the min and max x, y values of the cropping polygon:

xmin, xmax = int(xc.min()), int(np.ceil(xc.max()))
ymin, ymax = int(yc.min()), int(np.ceil(yc.max()))
trimmed = masked[ymin:ymax, xmin:xmax]

绘图:

from matplotlib import pyplot as plt

fig, ax = plt.subplots(2, 2)

ax[0,0].imshow(img, cmap=plt.cm.gray)
ax[0,0].set_title('original')
ax[0,1].imshow(mask, cmap=plt.cm.gray)
ax[0,1].set_title('mask')
ax[1,0].imshow(masked, cmap=plt.cm.gray)
ax[1,0].set_title('masked original')
ax[1,1].imshow(trimmed, cmap=plt.cm.gray)
ax[1,1].set_title('trimmed original')

plt.show()

enter image description here

相关问题 更多 >