我正在 python 中创建一个圆形掩码,如下所示:
import numpy as np
def make_mask(image, radius, center=(0, 0)):
r, c, d = image.shape
y, x = np.ogrid[-center[0]:r-center[0], -center[1]:r-center[1]]
mask = x*x + y*y <= radius*radius
array = np.zeros((r, c))
array[mask] = 1
return array
这将返回形状为 (r, c) 的掩码。我想要做的是有一个加权蒙版,其中图像中心的权重为 1(由中心参数给定)并向图像边缘线性减小。因此,他应该是在该行中在 0 和 1(不包括 0)之间计算的附加权重。我在想这应该是这样的:
distance = (center[0] - x)**2 + (center[1] - y)**2
# weigh it inversely to distance from center
mask = (x*x + y*y) * 1.0/distance
但是,这将导致除以 0,掩码也不会介于 0 和 1 之间。
最佳答案
首先,如果您希望权重为线性,您需要对距离求平方根(即,您所说的“距离”不是距离从中心开始,但它的平方,所以你应该将它重命名为 R_squared
之类的东西。所以:
R_squared = (center[0] - x)**2 + (center[1] - y)**2 # what you have for distance
r = sqrt(R_squared)
然后,因为它从 0
开始,而您希望它是 1
,所以向它添加 1
;但现在您已经添加了 1
缩放值,因此它是 1
,您希望结果为 0
。假设您希望它在距中心 L
的距离处为 0
,则您的等式为:
weight = 1 - r/L
此处为 1
,其中 r==0
和 0
,其中 r==L
。
关于python - 创建具有线性渐变的图像 mask ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28170603/