gpt4 book ai didi

python - 如何使用 numpy 有效地制作脉冲噪声图像?

转载 作者:行者123 更新时间:2023-12-02 16:19:11 24 4
gpt4 key购买 nike

我一直在尝试使用以下代码创建嘈杂的图像:

def toImpulse(img, coef=1.2): # img - > 3dim numpy array, returns impulse image
bmp = np.zeros(shape=(img.shape[0], img.shape[1], 1), dtype=np.float)
for i in range(img.shape[0]):
for j in range(img.shape[1]):
bmp[i][j] = sum(img[i][j]) / 3

在这里,我对 RGB channel 求和并使图像成为单 channel ?我想它可以写成 numpy.sum()
    sum_ = 0
max_ = np.amax(bmp)
final = np.zeros(img.shape)
for i in range(img.shape[0]):
for j in range(img.shape[1]):
sum_ += bmp[i][j]
if sum_ >= coef * max_:
final[i][j] = 1
sum_ -= coef * max_
else:
final[i][j] = 0

return final

但它在实时视频处理中出现了非常缓慢的情况。如何使用 NumPy 提高效率?这是该功能的工作示例
The original image
Noisy image

最佳答案

您的代码在我的机器上需要 539 毫秒。如果我使用 Numpy 计算 3 个颜色 channel 的平均值并避免将零写入输出图像,因为它已经像这样初始化为零:

def metoImpulse(img, coef=1.2):
# Get mean of the 3 colour channels
bmp = np.mean(img, axis=-1, dtype=np.float32)
sum_ = 0
max_ = np.amax(bmp)
final = np.zeros_like(img[...,0])
for i in range(img.shape[0]):
for j in range(img.shape[1]):
sum_ += bmp[i][j]
if sum_ >= coef * max_:
final[i][j] = 1
sum_ -= coef * max_
return final

时间从 539ms 下降到 257ms。如果我然后通过在我的函数之前添加一个装饰器来使用 Numba:
@jit(parallel=True)
def metoImpulse(img, coef=1.2):
# Get mean of the 3 colour channels
bmp = np.mean(img, axis=-1, dtype=np.float32)
sum_ = 0
max_ = np.amax(bmp)
final = np.zeros_like(img[...,0])
for i in range(img.shape[0]):
for j in range(img.shape[1]):
sum_ += bmp[i][j]
if sum_ >= coef * max_:
final[i][j] = 1
sum_ -= coef * max_
return final

时间从 257ms 下降到 1.11ms。

输入图像:

enter image description here

输出图像:

enter image description here

关于python - 如何使用 numpy 有效地制作脉冲噪声图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62100675/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com