【问题标题】:Fill image with nearest value within region用区域内最接近的值填充图像
【发布时间】:2020-05-30 12:11:09
【问题描述】:

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

我想过使用沿着meshgrid的线的东西作为起点来计算要在每个点填充的值的坐标,但具体方法不清楚。

【问题讨论】:

    标签: python numpy scikit-image


    【解决方案1】:

    使用 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
    

    关键部分是:

    • 使用np.mgrid 创建一个类似meshgrid 的索引数组xi, yi - 每个都与图像大小相同
    • 通过计算 xi, yi 计算最近边缘像素的坐标 xe, ye 数组
    • 通过下标图像替换值,如下所示:img[ye,xe]

    【讨论】:

    • 答案就在眼前。我曾经做过一些非常相似的事情,但我使用了 ogrid 而不是 mgrid。
    猜你喜欢
    • 2016-05-12
    • 1970-01-01
    • 1970-01-01
    • 2016-10-11
    • 1970-01-01
    • 2016-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多