Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 加速两幅图像的差异_Python_Python 3.x_Image_Difference - Fatal编程技术网

Python 加速两幅图像的差异

Python 加速两幅图像的差异,python,python-3.x,image,difference,Python,Python 3.x,Image,Difference,我有两个图像作为numpy数组,每个是180x180,有R,G,B值,总共97200个单独的值。我遍历每个像素和每个R,G,B;计算对应的两个像素之间的差值并求和为整数。大约需要5秒钟。如何加快程序的速度?使用numpy,您可以直接执行 result = (array1 - array2).sum() 您还可以仅在一个方向上计算 result = (array1 - array2).sum(axis=0) result = (array1 - array2).sum(axis=1) res

我有两个图像作为numpy数组,每个是180x180,有R,G,B值,总共97200个单独的值。我遍历每个像素和每个R,G,B;计算对应的两个像素之间的差值并求和为整数。大约需要5秒钟。如何加快程序的速度?

使用numpy,您可以直接执行

result = (array1 - array2).sum()
您还可以仅在一个方向上计算

result = (array1 - array2).sum(axis=0)

result = (array1 - array2).sum(axis=1)

result = (array1 - array2).sum(axis=2)
在我的旧电脑上,图像800x600大约需要0.003秒

cv2的示例,该示例将图像作为numpy数组提供

import cv2
import time

img1 = cv2.imread('image1.jpg')
img2 = cv2.imread('image2.jpg')

print('shape:', img1.shape)

start = time.time()

result = (img1 - img2).sum()

end = time.time()

print('result:', result)
print('  time:', end-start)
编辑:带有图像的numpy数组可能使用数据类型uint8,它只能使用值0..255,因此减法1-2可能会得到254,而不是-1。您可以将数据转换为int以获得负值和-1,而不是254。然后您可以使用abs或**2将负值转换为正值,以创建正确的和,如


所有这些计算仍然很快。

这似乎是GPU最快的一件事。对于较小的提升,您可以尝试多线程。您有很多库可以做,内置多线程,对于numpy+gpu,您有CuPyhow如何直接使用array1-array2.sum而不遍历像素?我添加了有关numpy数组可以使用的uint8的信息。
print(img1.dtype, img1.dtype)

img1 = img1.astype(int)
img2 = img2.astype(int)

diff = img1 - img2
print( diff.sum() )
print( (diff**2).sum() )
print( np.abs(diff).sum() )