Nick K
Nick K

Reputation: 35

How to convert an Image matrix into a vector in Matlab

I cant seem to figure this out: I need to reshape a matrix into a vector and so far I have this:

img = imread('image.png');
grayImage = rgb2gray(img);
imageArray = reshape(grayImage, r, c);

Which outputs something like:

imgVector=[1 2 3 4 5 6 7 8 9 0]

My problem is I need it to do something like this:

imgArray=[1 2 3
          4 5 6 
          7 8 9]

Reshaped into:

imgVector=[1 2 3 6 5 4 7 8 9]

I hope that make sense. Basically I need it to be unzipped so it goes from left to right and then right to left after the next row. Any help would be appreciated. Thank you in advance.

Upvotes: 1

Views: 5664

Answers (2)

tmpearce
tmpearce

Reputation: 12693

Fundamentally what you're trying to do is flip each row left-to-right, so the built-in function fliplr will do the trick.

To do it in a single step, just select every other row in your indexing operation:

>> imgArray=[1 2 3; 4 5 6; 7 8 9]

imgArray =

     1     2     3
     4     5     6
     7     8     9

>> imgArray(2:2:end,:)=fliplr(imgArray(2:2:end,:))

imgArray =

     1     2     3
     6     5     4
     7     8     9

Then you can turn it into a vector by reshaping.

imgVector=reshape(imgArray',1,[]);
 #%transpose the array----^

Since reshaping is done column-wise, transpose the array first to get it in the format you want.

Upvotes: 2

Benoit_11
Benoit_11

Reputation: 13945

You can use the fliplr function, which inverts the order of a vector. Here is a simple example:

A = [1 2 3;4 5 6;7 8 9];

A =

     1     2     3
     4     5     6
     7     8     9

A(2,:) = fliplr(A(2,:));

A =

     1     2     3
     6     5     4
     7     8     9

So could use a loop an flip every other row for your entire image. Hope that helps!

Upvotes: 1

Related Questions