Quickly process opencv image pixels using python interface

Using the python interface for OpenCV, you can easily access the image pixel using the [] operator, for example:

img = cv.LoadImage('test.jpg')
pixel = img[10,10]

the pixel variable is a python tuple object , for example (10,20,30) (for example, 3 channels), it is not very convenient to handle calculations, since the tuple type does not support the operator '-' or '+' . If I hope to make a substring on a pixel, for example 255 - (10,20,30) , I should code like this:

import numpy as np
pixel = tuple( np.array([255,255,255]) - np.array(pixel) )

is there a faster and easier solution?
One more question: is there a way to make a markup on all pixels, for example, using matrix substitution in Matlab: 255 - img (do not use the OpenCV build function).

+5
source share
1 answer

You can use the functions cv2array()/array2cv()from adapters.py in the opencv source distribution and do all your calculations using arrays numpy. 255 - imgarrworks in this case. Example (truncated version cv2array()for read-only arrays):

assert isinstance(img, cv.iplimage) and img.depth == cv.IPL_DEPTH_8U
a = np.frombuffer(img.tostring(), dtype=np.uint8)
a.shape = img.height, img.width, img.nChannels
print 255 - a
+3
source

All Articles