Ask Your Question
0

Pixel access through python interface

asked 2013-07-30 01:01:56 -0500

mrgloom gravatar image

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

edit retag flag offensive close merge delete

Comments

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

StevenPuttemans gravatar imageStevenPuttemans ( 2013-07-30 02:05:55 -0500 )edit

1 answer

Sort by ยป oldest newest most voted
4

answered 2013-07-30 03:03:06 -0500

berak gravatar image

updated 2013-07-30 03:06:01 -0500

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)
edit flag offensive delete link more

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 ( 2013-07-30 03:07:12 -0500 )edit
1

Jep, the python interface is nice :)

Guanta gravatar imageGuanta ( 2013-07-30 03:30:49 -0500 )edit
1

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

mrgloom gravatar imagemrgloom ( 2013-07-30 07:29:51 -0500 )edit
Login/Signup to Answer

Question Tools

Stats

Asked: 2013-07-30 01:01:56 -0500

Seen: 215 times

Last updated: Jul 30 '13