5

Using python-interface for OpenCV, one can easily access the pixel of image using [] operator,like this:

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

variable pixel here is a python tuple object like (10,20,30) (3 channels for example), it's not very convenient to process computation since tuple type does not support operator '-' or '+'. If I hope to do a substruction on a pixel like 255 - (10,20,30), I must code like this:

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

is there a faster and easier solution?
Another qustion : is there a way to make a substraction on all pixels, like using a matrix substraction in Matlab: 255 - img (don't use OpenCV build-in function).

1 Answer 1

3

You could use cv2array()/array2cv() functions from adaptors.py in the opencv source distribution and perform all your computation using numpy arrays. 255 - imgarr works in this case. Example (stripped-down version of 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
Sign up to request clarification or add additional context in comments.

5 Comments

my opencv version is 2.1, I found adaptors.py in \OpenCV2.1\interfaces\swig\python, and there was not a function called cv2array() or array2cv()
@PinkyJie: google.com/…
@PinkyJie: On the other hand the above method might be outdated. Does your version have cv.fromarray() function? What do you get on numpy.asarray(img)? opencv.willowgarage.com/documentation/python/…
I installed opencv using "OpenCV-2.1.0-win32-vs2008.exe", a pre-compiled edition, so no cv.fromarray() function, and numpy.asarray(img) return a iplimage object array, not numpy.ndarray.
@PinkyJie: I've added example code in case np.asarray() doesn't return anything useful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.