A few days back, I started using new OpenCV-Python interface, cv2
.
My question is regarding the comparison of cv
and cv2
inter
The image returned by cv2.imread() is an array object of NumPy. So you can use NumPy's functions to speedup calculation.
The following program shows how to speedup your origin for loop version by using item(), itemset() method of ndarray object.
import time
import numpy as np
import cv2
gray = cv2.imread('lena_full.jpg',0)
height, width = gray.shape
h = np.empty((height,width,3), np.uint8)
t = time.time()
for i in xrange(height):
for j in xrange(width):
k = gray.item(i, j)
if k == 127:
h.itemset(i, j, 0, 255)
h.itemset(i, j, 1, 255)
h.itemset(i, j, 2, 255)
elif k > 127:
h.itemset(i, j, 0, 0)
h.itemset(i, j, 1, 0)
h.itemset(i, j, 2, 255-k)
else:
h.itemset(i, j, 0, k)
h.itemset(i, j, 1, 0)
h.itemset(i, j, 2, 0)
print time.time()-t
And the following program show how to create the palette first, and use NumPy's array index to get the result:
t = time.time()
palette = []
for i in xrange(256):
if i == 127:
palette.append((255, 255, 255))
elif i > 127:
palette.append((0,0,255-i))
else:
palette.append((i, 0, 0))
palette = np.array(palette, np.uint8)
h2 = palette[gray]
print time.time() - t
print np.all(h==h2)
The output is:
0.453000068665
0.0309998989105
True
The cv version output is :
0.468999862671
Note: the length of axis 0 is the height of the image, the length of axis 1 is the width of the image