使用区域内最近的值填充图像

2024-05-14 06:50:09 发布

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

我想用圆内最近的值填充圆形区域外的图像。其效果类似于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代码中循环每个像素;典型的图像是数千万像素)

我曾想过使用网格线沿线的东西作为起点来计算要在每个点上填充的值的坐标,但方法不清楚


Tags: 代码in图像区域imgforrange圆形
1条回答
网友
1楼 · 发布于 2024-05-14 06:50:09

使用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-每个数组与图像大小相同
  • 通过计算席曦,Yi
  • 计算最近边缘像素的坐标{{CD3}}的数组
  • 通过为图像下标来替换值,如下所示:img[ye,xe]

相关问题 更多 >

    热门问题