gpt4 book ai didi

python - Python Opencv img.item()性能太慢

转载 作者:行者123 更新时间:2023-12-02 16:47:20 25 4
gpt4 key购买 nike

我写了这个小代码来比较两个100x100 jpeg图像的像素灰度值。
但是,性能令人失望(10,000次比较为1.5秒)。有没有办法获得更好的性能?

这是代码:

import cv2
import numpy as np
import math
import datetime


img1 = cv2.imread('Testbild 2014-08-23 17:27:25.141362.jpeg', cv2.IMREAD_GRAYSCALE)
img2 = cv2.imread('Testbild 2014-08-23 17:27:25.061802.jpeg', cv2.IMREAD_GRAYSCALE)

height, width =img1.shape
cnt = 0
threshold = 10

print("start:" + str(datetime.datetime.now()))
for y in range(0 , height):
for x in range(0 , width):
val1 = img1.item(y,x)
val2 = img2.item(y,x)
diff_abs = math.fabs(int(val1)-int(val2))
if diff_abs > threshold:
cnt += 1
if x == height and y == width:
break
if x == height:
x=0
if y == width:
y=0

print("end:" + str(datetime.datetime.now()))
print("Result: " + str(cnt))

非常感谢您的回答!

最佳答案

双循环:

for y in range(0 , height):
for x in range(0 , width):
val1 = img1.item(y,x)
val2 = img2.item(y,x)
diff_abs = math.fabs(int(val1)-int(val2))
if diff_abs > threshold:
cnt += 1
if x == height and y == width:
break
if x == height:
x=0
if y == width:
y=0

可以替换为:
diff_abs = np.abs(img1-img2)
cnt = (diff_abs > threshold).sum()

这利用了NumPy数组执行 fast element-wise arithmetic的能力。

条件
 x == height and y == width

永远都不是真的。如果为 height < width,则 y将永远不会等于 width(因为 yrange(0, height)中)。如果为 height > width,则 x将永远不会等于 height。如果是 height == width,那么 xy都不等于 height

条件
    if x == height:
x=0

没有任何用处,因为即使 x == height,对 x的分配也会在循环的下一次迭代中丢失。

同样的道理
    if y == width:
y=0

关于python - Python Opencv img.item()性能太慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25467693/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com