Python Opencv img.item()性能太慢了

flo*_*flo 0 python opencv numpy

我写了这个小代码来比较两个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))
Run Code Online (Sandbox Code Playgroud)

非常感谢您的回答!

unu*_*tbu 5

双循环:

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     
Run Code Online (Sandbox Code Playgroud)

可以替换为:

diff_abs = np.abs(img1-img2)
cnt = (diff_abs > threshold).sum()
Run Code Online (Sandbox Code Playgroud)

这利用了NumPy数组执行快速逐元素算术的能力.


条件

 x == height and y == width
Run Code Online (Sandbox Code Playgroud)

从来都不是真的.如果height < width,则y永远不会相等width(因为yrange(0, height)).如果height > width,那么x永远不会平等height.如果height == width,那么既x不会y也不会平等height.


条件

    if x == height:
        x=0
Run Code Online (Sandbox Code Playgroud)

没有任何用处,因为即使在循环的下一次迭代中丢失x == height了赋值x.

同样的道理

    if y == width:
        y=0     
Run Code Online (Sandbox Code Playgroud)