根据距椭圆中心的距离计算权重

computing weight based on distance from centre of ellipse

我之前使用的是圆形图像蒙版,我根据与圆心的距离计算权重如下:

import numpy as np
def create_mask(image, radius, center=(0, 0)):
    r, c, d = image.shape
    x, y = np.ogrid[:r, :c]
    distance = np.sqrt((x-center[0])**2 + (y-center[1])**2)
    m = distance < radius
    distance[m] = 1.0 - distance[m]/radius
    array = np.zeros((r, c))
    array[m] = distance[m]
    return array

这基本上是将高度权重设置在中心,权重向边缘线性下降。

现在,我想用椭圆做一些类似的事情。同样,椭圆在两个维度上可以有非常不同的半径,我希望重量也随着距离线性下降。但是,无论长半径还是短半径,我都希望权重向边缘衰减。我猜我需要包含一个基于两个半径的权重才能实现这一点,但无法弄清楚。

我不确定线性权重,但您可以使用(我确信有更有效的方法)实现从 1 到 0 的连续数组权重

ellipse = lambda x0, y0, r_x, r_y: lambda x, y: ((x - x0) / r_x)**2 + ((y - y0) / r_y)**2

def gen_ellipse(el, lower, upper, step):
    coords = np.arange(lower, upper, step)
    x, y = np.meshgrid(coords, coords)
    mask = el(x, y)
    mask[np.where(mask > 1)] = 0
    return 1 - mask

例如:

> %pylab
> el = ellipse(0.0, 0.0, 0.3, 0.8)
> mask = gen_ellipse(el, -1.0, 1.0, 0.0025)
> imshow(mask, cmap=get_cmap('Greys'))

其中黑色为 1,白色为 0。