AL B
AL B

Reputation: 223

replacing array values for images-matlab

I have an image with an item in it and I am trying to find its edge. I have applied an edge detection algorithm and I have successfully found the trace around the image using regionprops. I also have the pixels inside of the traced shape. What I want to do is replace all the other pixels with a black background. A is an RGB image and Aseg is a segmented image

A1=rgb2gray(A)
pixels=regionprops(logical(Aseg),'PixelList');

I know how to plot the pixels that I need on top of the original image

imshow(A1);hold on
plot(pixels.PixelList(:,1),pixels.PixelList(:,2))

But I want to plot just the pixels i want to keep with their original value and just replace all the others with a black background and I can not find a way to do it. Anyone has any suggestions? Thank you.

Upvotes: 0

Views: 57

Answers (1)

rayryeng
rayryeng

Reputation: 104464

If all you want is to maintain the pixels of the shape and set everything else to black, simply create a new blank image and copy the locations from the original image over to the new image, and leave everything else as black. This essentially sets all of the other locations to black while leaving the desired region intact.

You can achieve that by sub2ind to generate linear indices to directly access your image and copy those values over into the new image.

As such, try something like this:

Anew = zeros(size(A1), class(A1));
ind = sub2ind(size(A1), pixels.PixelList(:,2), pixels.PixelList(:,1)); 
Anew(ind) = A1(ind);

Anew contains the new image with the background pixels set to black. PixelList is a structure where the first column are the x or column coordinates and the second column are the y or row coordinates. With sub2ind, you must specify the rows first, then the columns after which is why we index the second column first followed by the first first column after.

Alternatively, you can achieve the same thing using logical indexing by creating a sparse matrix that is logical, then using this matrix to index directly into the image and set the proper locations:

Anew = zeros(size(A1), class(A1));
ind = logical(sparse(pixels.PixelList(:,2), pixels.PixelList(:,1), 1, size(A1,1), size(A1,2)));
Anew(ind) = A1(ind);

Note that the rows and columns ordering is the same as using sub2ind.

Upvotes: 2

Related Questions