【问题标题】:How to increase pixel math speed using NumPy如何使用 NumPy 提高像素数学速度
【发布时间】:2015-03-11 20:38:06
【问题描述】:

我正在寻求有关如何提高此计算速度的帮助。我要做的是访问每个像素并对其进行一些数学运算,然后使用新的像素计算创建一个新图像。我通过几千张小图像运行这个需要 1 小时以上的时间。任何帮助将不胜感激,谢谢。

image=cv2.imread('image.png')

height, width, depth = image.shape

for i in range(0, height):  
    for j in range (0, width):
        B = float(image.item(i,j,0)) #blue channel of image
        R=float(image.item(i,j,2)) #red channel of image

        num = R-B
        den = R+B

        if den == 0:
            NEW=1
        else:
            NEW = ((num/den)*255.0)

        NEW = min(NEW,255.0)
        NEW = max(NEW,0.0)
        image[i,j] = NEW  #Sets all BGR channels to NEW value

cv2.imwrite('newImage.png',image)

【问题讨论】:

    标签: python performance opencv numpy


    【解决方案1】:

    删除双重for-loop。使用 NumPy 加快速度的关键是一次对整个数组进行操作:

    image = cv2.imread('image.png')    
    height, width, depth = image.shape
    
    image = image.astype('float')
    B, G, R = image[:, :, 0], image[:, :, 1], image[:, :, 2]
    num = R - B
    den = R + B
    image = np.where(den == 0, 1, (num/den)*255.0).clip(0.0, 255.0)
    
    cv2.imwrite('newImage.png',image)
    

    通过在整个数组上调用 NumPy 函数(而不是对标量像素值执行 Python 操作),您可以将大部分计算工作卸载到由 NumPy 函数调用的快速 C/C++/Cython(或 Fortran)编译代码。

    【讨论】:

    • 非常感谢,现在只需不到 5 分钟。是的,我认为这是双 for 循环,我只是不确定如何继续使用 NumPy。再次感谢
    猜你喜欢
    • 2018-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-30
    • 2019-08-11
    • 2021-09-18
    • 2013-10-20
    • 1970-01-01
    相关资源
    最近更新 更多