我正在写一个脚本来修改一个RGB图像的亮度使用NumPy和CV2通过转换从RGB到YCrCb和回来。然而,我正在使用的循环需要一段时间才能执行,我想知道是否有更快的方法。
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)实现阈值比较的嵌套循环至少需要5-7秒才能执行。有没有更快的方法来实现这个功能?
发布于 2014-01-30 22:55:44
我们的想法是创建一个,它允许您使用numpy的矢量化。由于形状为(n,m,3),因此使用[:,:,0]遍历前两个维度并获取最后一个维度的第一个索引
idx = image[:,:,0] > threshold
image[idx,0] = threshold发布于 2014-01-30 23:29:04
您可以使用clip
用法:
result = im.copy()
result[..., 0] = np.clip(im[..., 0], 0, threshold)或就地修改:
np.clip(im[..., 0], 0, threshold, out=im[..., 0])发布于 2014-01-31 00:26:22
import numpy as np
image[..., 0] = np.minimum(image[..., 0], threshold)编辑:对不起,我还不能添加评论。我昨天感觉很懒。关于就地修改是正确的,但它是相当明显的,或者你不需要它。懒惰是对一个懒惰问题的回答--在numpy中有一个“一切”的函数--只要看看文档就知道了。
https://stackoverflow.com/questions/21459758
复制相似问题