MATLAB: How to extract pixel data from a RGB / Grayscale image by specifying a region of interest

Image Processing Toolboxmaskroiroipolyshape

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.

Best Answer

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);