使用 NumPy(或 SciPy)裁剪部分图像 [英] Crop out partial image using NumPy (or SciPy)
本文介绍了使用 NumPy(或 SciPy)裁剪部分图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用 numpy
或 scipy
(我没有使用 OpenCV
)我试图从图像中裁剪一个区域.
Using numpy
or scipy
(I am not using OpenCV
) I am trying to crop a region out of an image.
例如,我有这个:
我想得到这个:
是否有类似 cropPolygon(image, vertices=[(1,2),(3,4)...])
和 numpy
或 SciPy
?
Is there something like cropPolygon(image, vertices=[(1,2),(3,4)...])
with numpy
or SciPy
?
推荐答案
你在使用 matplotlib 吗?
Are you using matplotlib?
我之前采用的一种方法是使用 matplotlib.path.Path
的 .contains_points()
方法来构造一个布尔掩码,然后可以用于索引到图像数组中.
One approach I've taken previously is to use the .contains_points()
method of a matplotlib.path.Path
to construct a boolean mask, which can then be used to index into the image array.
例如:
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()
这篇关于使用 NumPy(或 SciPy)裁剪部分图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文