簡體   English   中英

Python Opencv img.item()性能太慢

[英]Python Opencv img.item() performance too slow

我寫了這個小代碼來比較兩個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數組執行快速逐元素運算的能力。


條件

 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     

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM