Ask Your Question
0

Accessing pixels in a Mat vector

asked 2018-11-09 07:48:12 -0600

Th3_noob gravatar image

I have reshape a 2d grayscale image to a 1d Mat.I want to access and change each pixel.Each pixel should be 0-255

Mat input_img = imread(argv[1], IMREAD_GRAYSCALE); 
Mat input_vector = input_img.reshape(0,1); 
std::cout << input_1d_vector.at<int>(0,1);

However it is not ouputing a sensible pixel value.My apologies if its a dumb question , i am new with opencv

edit retag flag offensive close merge delete

Comments

what are you really trying to achieve here ? what is the purpose of it ?

I want to access and change each pixel.

NO, you shouldn't do things per-pixel at all. XY-problem here !

berak gravatar imageberak ( 2018-11-09 07:49:49 -0600 )edit

I want to convert the 2d representation ofan image to 1d to apply RLE(run length encoding) on it

Th3_noob gravatar imageTh3_noob ( 2018-11-09 07:59:01 -0600 )edit

different story, then. ;)

is this "homework" ? (smells pretty much like it !)

berak gravatar imageberak ( 2018-11-09 08:14:43 -0600 )edit

No its not homework , it just need help in accessing the pixels in the Mat , not with RLE

Th3_noob gravatar imageTh3_noob ( 2018-11-09 08:17:23 -0600 )edit

then again no, you shouldn't.

opencv is a high level matrix library. use appropriate functions, don't reinvent square wheels !

berak gravatar imageberak ( 2018-11-09 08:24:49 -0600 )edit

2 answers

Sort by ยป oldest newest most voted
1

answered 2018-11-09 08:24:05 -0600

berak gravatar image

so, the correct way to access uchar, single channel image would have been:

mat.at<uchar>(y,x); // NOT int !

but the faster way to do it would be:

uchar *ptr = mat.ptr<uchar>(0); // pointer to row 0
// you can index it like ptr[0] ... ptr[mat.cols-1]

and the reason you see garbage, when printing it out is, that cout treats (u)chars as ascii symbols, so you need to cast it:

 cout << (int)value << endl;

but better, print out the whole Mat:

cout << mat << endl;

(no problem with types any more !)

edit flag offensive delete link more

Comments

Urgh......now i feel stupid.Thanks mate

Th3_noob gravatar imageTh3_noob ( 2018-11-09 08:26:37 -0600 )edit
0

answered 2018-11-09 07:53:26 -0600

holger gravatar image

This question was answered before : http://answers.opencv.org/question/19... This shows also a performant way to do it(the thing berak meant with "xy" problem i think).

edit flag offensive delete link more

Comments

somewhat, yes ;)

but let's see, what @Th3_noob says ...

berak gravatar imageberak ( 2018-11-09 07:56:51 -0600 )edit

He understood it and said thanks XD

holger gravatar imageholger ( 2018-11-09 11:39:21 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2018-11-09 07:48:12 -0600

Seen: 2,964 times

Last updated: Nov 09 '18