2015-01-13 38 views
0

我正在寻找如何提高此计算速度的帮助。我想要做的是访问每个像素并对其进行一些运算,然后用新像素计算创建一个新图像。我通过几千张小图片来运行这个过程,花费1小时+。任何帮助将不胜感激,谢谢。如何使用NumPy提高像素数学速度

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) 

回答

4

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

+0

非常感谢,现在的时间不到5分钟。是的,我认为这是双循环,我只是不知道如何继续NumPy。再次感谢 – BFlint