python - 创建具有线性渐变的图像 mask

标签 python image-processing numpy

我正在 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==00,其中 r==L

关于python - 创建具有线性渐变的图像 mask ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28170603/

相关文章:

使用 win32com 的 Python 不会使用所需的加载项更新 Excel 工作表

python - 在 jupyter notebook 中水平打印 Quantile 函数的输出

python - YUV420p转其他格式,色偏问题

python - 获取 numpy 数组中非零元素的数量?

python - reshape LSTM 的 Keras 输入

python - 如何删除重复条目

python - 如何处理 python 杂散属性赋值

python - OpenCV 版本 4.1.0 drawContours 错误 : (-215:Assertion failed) npoints > 0 in function 'drawContours'

image-processing - 图像处理 - 哪种 OpenCV 算法适合我的需要?

python - 被 pandas dtype 转换为 np.float16 值 2053 变成 2052 感到困惑