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

Hig*_*ler 6 python numpy scipy

使用numpyscipy(我没有使用OpenCV)我试图从图像中裁剪一个区域.

例如,我有这个:

在此输入图像描述

我想得到这个:

在此输入图像描述

有什么样cropPolygon(image, vertices=[(1,2),(3,4)...])numpySciPy

ali*_*i_m 13

你在使用matplotlib吗?

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

例如:

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]
Run Code Online (Sandbox Code Playgroud)

绘图:

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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述