How can I extract pixel data from a RGB / Grayscale image by specifying a region of interest?

2 views (last 30 days)
I would like to define a region of interest and then count the number of pixels in it, as well as do various calculations on the region. The region of interest (ROI) could be either a rectangle or an irregular shape.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 27 Jun 2009
There are three different ways this can be achieved. The three examples are shown below:
%%Method 1: Sets image to be transparent except the ROI
I = imread('peppers.png');
image(I); axis off;
disp('please selct the Region Of Interest')
ROI = roipoly(I); % select a closed polygon
myImage = findall(gcf,'type','image');
set(myImage,'AlphaData',ROI);
Method 2
I= imread('peppers.png');
image(I); axis off;
disp('please selct the Region Of Interest')
ROI = double(roipoly); % select a closed polygon
ROI = uint8(ROI); % since original image was of type uint8
figure
I2 = zeros(size(I)); % create a new image
I2(:,:,1) = ROI.*I(:,:,1);
I2(:,:,2) = ROI.*I(:,:,2);
I2(:,:,3) = ROI.*I(:,:,3);
image(uint8(I2)); axis off;
%%Method 3: Utilizes the IMCROP functionality
I= imread('peppers.png');
imshow(I);
rect = [290 160 220 165];
I2= imcrop(I,rect);
figure
imshow(I2);

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!