Python NumPy - 实现阈值上限的更快方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21459758/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:54:04  来源:igfitidea点击:

NumPy - Faster way to implement threshold value ceiling

pythonimage-processingnumpy

提问by Jason

I'm writing a script to modify the luminance of a RGB image using NumPy and CV2 via converting from RGB to YCrCb and back again. However, the loop I'm using takes a while to execute, and am wondering if there is a faster way.

我正在编写一个脚本,通过从 RGB 转换为 YCrCb 并再次转换回来,使用 NumPy 和 CV2 修改 RGB 图像的亮度。但是,我使用的循环需要一段时间才能执行,我想知道是否有更快的方法。

import cv2 as cv, numpy as np

threshold = 64
image = cv.imread("motorist.jpg", -1)
image.shape # Evaluates to (1000, 1500, 3)

im = cv.cvtColor(image, cv.COLOR_RGB2YCR_CB)

for row in image:
    for col in row:
        if col[0] > threshold:
            col[0] = threshold

image = cv.cvtColor(im, cv.COLOR_YCR_CB2RGB)
cv.imwrite("motorist_filtered.jpg", image)

That nested loop implementing the threshold comparison takes at least 5-7 seconds to execute. Is there a faster method to implement this functionality?

执行阈值比较的嵌套循环至少需要 5-7 秒才能执行。有没有更快的方法来实现这个功能?

采纳答案by Hooked

The idea is to create a maskthat lets you use the numpy's vectorization. Since the shape is (n,m,3), loop over the first two dimensions and grab the first index of the last dimension with [:,:,0]

这个想法是创建一个掩码,让您可以使用 numpy 的矢量化。由于形状是(n,m,3),循环前两个维度并使用最后一个维度的第一个索引[:,:,0]

idx = image[:,:,0] > threshold
image[idx,0] = threshold

回答by YXD

You can use clip:

您可以使用clip

Usage:

用法:

result = im.copy()
result[..., 0] = np.clip(im[..., 0], 0, threshold)

Or to modify in-place:

或者就地修改:

np.clip(im[..., 0], 0, threshold, out=im[..., 0])

回答by Martin

import numpy as np

image[..., 0] = np.minimum(image[..., 0], threshold)

Edit: Sorry, I can't add comments yet. I was feeling lazy yesterday. True about the in place modification but it is rather obvious or you don't need it. And laziness was a response to a lazy question - there is a function for 'everything' in numpy - just check the docs.

编辑:抱歉,我还不能添加评论。我昨天感觉很懒。关于就地修改是正确的,但它很明显,或者你不需要它。懒惰是对一个懒惰问题的回应——numpy 中有一个“一切”的功能——只需查看文档即可。