Ask Your Question
0

Pixel access through python interface

asked Jul 30 '13

mrgloom gravatar image

Can anyone give a code snippet of image pixel access through python interface? (maybe fasterst and simplest methods also differ)

Preview: (hide)

Comments

Is it possible to use the Mat_ class in the python interface? The at operator isn't available I noticed...

StevenPuttemans gravatar imageStevenPuttemans (Jul 30 '13)edit

1 answer

Sort by » oldest newest most voted
4

answered Jul 30 '13

berak gravatar image

updated Jul 30 '13

there is no Mat (or Mat_ even) in cv2, instead it's numpy arrays all the way down.

>>> import cv2
>>> import numpy as np
>>> m =  cv2.imread("m2.bmp")
>>> np.shape(m)
(480, 640, 3)

you'd access them like img[y][x] = 3, or green = img[y][x][1] (for color), it's the same row,col convention as for cv::Mat

>>> m[2][2][1]
68

there's range operators too (if you need a submat / roi) : roi = img[y:Y, x:X]

>>> m[2:4, 3:6]
array([[[54, 63, 49],
        [52, 59, 47],
        [51, 58, 46]],

       [[41, 50, 36],
        [45, 52, 40],
        [47, 54, 42]]], dtype=uint8)

and you can even slice them, i.e to get only the last channel:

>>> m[:,:,2]
array([[ 0,  0,  0, ...,  0,  0,  0],
       [36, 39, 38, ...,  0,  0,  0],
       [59, 59, 54, ...,  0,  0,  0],
       ...,
       [ 0,  0,  0, ...,  0,  0,  0],
       [ 3,  3,  3, ...,  0,  0,  0],
       [ 3,  3,  3, ...,  0,  0,  0]], dtype=uint8)
Preview: (hide)

Comments

This is clearly a Matlab kinda implementation :) Didn't know about this one... Time to have a closer look at the python interface. It seems quite interesting.

StevenPuttemans gravatar imageStevenPuttemans (Jul 30 '13)edit
1

Jep, the python interface is nice :)

Guanta gravatar imageGuanta (Jul 30 '13)edit
1

thanks that works like m[10][12] = [100,1,34]

mrgloom gravatar imagemrgloom (Jul 30 '13)edit

Question Tools

Stats

Asked: Jul 30 '13

Seen: 775 times

Last updated: Jul 30 '13