Opencv ... retrieving data in IPLImage or CvMat

I am making some simple programs with opencv in python. I want to write some algorithms myself, so you need to get the raw image data inside the image. I can’t just make an image [i, j], for example, how can I get the numbers?

thanks

+4
source share
3 answers

A quick example of using LoadImageM to load an image file directly into cvmat :

 import cv path = 'stack.png' mat = cv.LoadImageM(path, cv.CV_LOAD_IMAGE_UNCHANGED) x, y = 42, 6 print type(mat) print mat[y, x] 

Output:

 <type 'cv.cvmat'> (21.0, 122.0, 254.0) 

A quick example showing how several or more color channels are 0.5 :

 for x in xrange(mat.cols): for y in xrange(mat.rows): # multiply all 3 components by 0.5 mat[y, x] = tuple(c*0.5 for c in mat[y, x]) # or multiply only the red component by 0.5 b, g, r = mat[y, x] mat[y, x] = (b, g, r * 0.5) 
+5
source

Both CvMat and IplImage provide tostring methods that return a string representing raw data. Using image data, you can figure out how to interpret string data as a matrix.

You can use fromarray to convert a data string back to an image object.

To convert a string to an array, consider using the array module in Python. For instance:

 array.array('B', CvMat.tostring()) # 'B' is unsigned char, for rgb8 images 

To get a "step" between pixels, use:

 stride = CvMat.step / CvMat.cols 

Then a typical indexing of the array to produce individual pixels. You probably want to wrap it all in a class that hides all the unpleasant complexity.

+1
source

I don't know opencv python bindings, but in C or C ++ you should get a buffer pointer stored in IplImage. This buffer is encoded according to the image format (also stored in IplImage). For RGB, you have a byte for R, a byte for G, a byte for B, etc.

Look at the python bindings API, you will find how to access the buffer, and then you can get the pixel information.

my2c

0
source

All Articles