python - 如何使用NumPy提高像素数学速度

标签 python performance opencv numpy

我正在寻求有关如何提高此计算速度的帮助。我想做的是访问每个像素并对其进行一些数学运算,然后使用新的像素计算来创建新图像。我正在通过数千个小图像来运行此过程,这些过程需要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)

最佳答案

删除双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)编译代码中。

关于python - 如何使用NumPy提高像素数学速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27929780/

相关文章:

python - 为什么Django说没有名为views的模块?

c++ - cv::Mat 中 cv::Point 的 OpenCV rgb 值

c++ - OpenCV IP 摄像机应用程序崩溃 [h264 @ 0xxxxx] 访问单元中缺少图片

python - 从 Django 访问用户主目录

python - 如何忽略函数返回的其余参数?

c# - 为什么静态 RegEx 比实例 RegEx 慢?

c# - 如何最好地确定新应用程序的系统要求?

c++ - float 乘法 : LOSING speed with AVX against SSE?

c++ - CUDA 相当于 OpenCV 3 中的 estimateRigidTransform

Python 在 fetchone 上运行缓慢,在 fetchall 上挂起