Opencv cv2.absdiff(img1, img2).sum() without temporary img

jshepherd picture jshepherd · Jul 24, 2013 · Viewed 19.4k times · Source

Is it possible to calculate cv2.absdiff(img1, img2).sum() without temporary img ?

I have a video stream and I need some kind of image stabilization on the begining of my processing. The absdiff gives fast and error dependent result on check different placement vectors with two following images, but I have to create, write and read a temporary image which one is used only for calculate the img.sum(). So it would be fine to eliminate these memory allocation, writing and reading steps.

def calcMatch(img1, img2):
    diff = cv2.absdiff(img1, img2)
    return diff.sum()

Solution in python

import cv2
import time

img = cv2.imread('test.jpg')
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img1 = img[10:330, 10:870]
img2 = img[20:340, 20:880]

start = time.clock()
d = cv2.absdiff(img1, img2)
s = d.sum()
t = time.clock() - start
print 'with absdiff ', t
print s

start = time.clock()
s = cv2.norm(img1, img2, cv2.NORM_L1)
t = time.clock() - start
print 'with norm L1 ',  t
print s

It gives significant speed up as on my laptop with a very stable ratio:
with absdiff 0.00207574457822
4315120
with norm L1 0.000226647018223
4315120.0

Answer

jet47 picture jet47 · Jul 24, 2013

Try norm function with NORM_L1 norm. C++ code:

double res = cv::norm(img1, img2, cv::NORM_L1);