我想用圆形内的最近值填充圆形区域外的图像。效果类似于skimage的mode ='edge',但适用于图像的圆形区域而不是矩形区域。
执行正确操作的简单代码-非常缓慢:
def circle_pad(img, xc, yc, r):
img_out = img.copy()
for i in range(img.shape[0]):
for j in range(img.shape[1]):
d = math.sqrt( (i-yc)**2 + (j-xc)**2 )
if d > r:
i1, j1 = int( yc + (i-yc)*(r/d) ), int( xc + (j-xc)*(r/d) )
img_out[i,j] = img[i1,j1]
return img_out
如何使用numpy加快速度? (可能避免在python代码中循环遍历每个像素;典型的图像是数千万个像素)
我曾考虑使用沿网格网格线的东西作为起点来计算要在每个点处填充的值的坐标,但方法尚不清楚。
使用mgrid解决-不漂亮,但速度很快。以防万一它对于其他具有类似图像处理问题的人为例有用:
def circle_pad(img, xc, yc, r):
mg = np.mgrid[:img.shape[0],0:img.shape[1]]
yi, xi = mg[0,:,:], mg[1,:,:]
mask = ((yi-yc)**2 + (xi-xc)**2) < r**2
d = np.sqrt( (yi-yc)**2 + (xi-xc)**2 )
d = np.clip(d, r, None)
ye = yc + (yi-yc)*(r/d)
xe = xc + (xi-xc)*(r/d)
ye = np.clip(ye.astype(int), 0, img.shape[0])
xe = np.clip(xe.astype(int), 0, img.shape[1])
img_out = img * mask + img[ye,xe] * (~mask)
return img_out
关键部分是:
xi, yi
创建类似于网格的索引数组np.mgrid
-每个具有与图像相同的大小xe, ye
的数组img[ye,xe]