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

Illustration
sudheer_sinha - 2022-02-28T12:29:46+00:00
Question: How can I extract pixel data from a RGB / Grayscale image by specifying a region of interest?

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.  

Expert Answer

Profile picture of Prashant Kumar Prashant Kumar answered . 2025-11-20

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.webp');

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.webp'); 

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.webp');

imshow(I);

rect = [290 160 220 165];

I2= imcrop(I,rect);

figure

imshow(I2);

 


Not satisfied with the answer ?? ASK NOW

Get a Free Consultation or a Sample Assignment Review!