Pixel access through python interface
Can anyone give a code snippet of image pixel access through python interface? (maybe fasterst and simplest methods also differ)
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)
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.
Asked: 2013-07-30 01:01:56 -0600
Seen: 767 times
Last updated: Jul 30 '13
How to access pixel values of CV_32F/CV_64F Mat?
Accessing pixels in Mat using Android (Java API)
What is the most effective way to access cv::Mat elements in a loop?
Area of a single pixel object in OpenCV
Weird result while finding angle
cv2.perspectiveTransform() with Python
Is it possible to use the Mat_ class in the python interface? The at operator isn't available I noticed...