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

使用NumPy(或SciPy)裁剪出部分图像,第1张

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

你在用matplotlib吗?我以前采用的一种方法是使用

.containsu points()
方法
matplotlib.path.path路径
构造一个布尔掩码,然后
用于索引到图像数组中。
例如:

import numpy as npfrom matplotlib.path import Pathfrom scipy.misc import lenaimg = lena()# vertices of the cropping polygonxc = 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 imagenr, nc = img.shapeygrid, xgrid = np.mgrid[:nr, :nc]xypix = np.vstack((xgrid.ravel(), ygrid.ravel())).T# construct a Path from the verticespth = Path(xycrop, closed=False)# test which pixels fall within the pathmask = pth.contains_points(xypix)# reshape to the same size as the imagemask = mask.reshape(img.shape)# create a masked arraymasked = 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]

Plotting:

from matplotlib import pyplot as pltfig, 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()


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5653987.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存