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

S
sudheer_sinha · Feb 28, 2022 · 2.3K views
Question
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 PhD Expert
Answered Aug 24, 2026

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

 

100% Run Guarantee 3-Hour Fast-Track Delivery

Need a Custom Version or Complete Simulation for This Problem?

Our 500+ PhD engineers build, debug, and optimize working MATLAB scripts and Simulink (.slx) models tailored to your exact assignment rubrics with zero plagiarism.

Tested on MATLAB R2024b / R2026a
Turnitin 0% Plagiarism Report
Free 7-Day Revisions Guarantee
Have a different question? Ask here

Get a Free Consultation or a Sample Assignment Review!