Discussion:
Extracting a ROI from an image.
(too old to reply)
Kinnu
2010-11-27 08:53:04 UTC
Permalink
Hi,

I have a folder of images of similar kind and I need to extract a fixed size(say 100X100) ROI(region of interest) from all the images simultaneously.

I am having the code to read the images from the sub folders.
a = dir;
curdir = pwd;
for k=1:size(a,1)
if a(k).isdir && ~strcmp(a(k).name,'.') && ~strcmp(a(k).name,'..')
cd([curdir '\' a(k).name])
b = dir;
for l=1:size(b,1)
if ~isempty(findstr(b(l).name,'.png')) && ~b(l).isdir
img = imread(b(l).name);
%XXXXXXXXXXXXXX
end
end
end
end
Please help me.

Thanks,
Kiran.
Kinnu
2010-11-27 10:06:04 UTC
Permalink
Post by Kinnu
Hi,
I have a folder of images of similar kind and I need to extract a fixed size(say 100X100) ROI(region of interest) from all the images simultaneously.
I am having the code to read the images from the sub folders.
a = dir;
curdir = pwd;
for k=1:size(a,1)
if a(k).isdir && ~strcmp(a(k).name,'.') && ~strcmp(a(k).name,'..')
cd([curdir '\' a(k).name])
b = dir;
for l=1:size(b,1)
if ~isempty(findstr(b(l).name,'.png')) && ~b(l).isdir
img = imread(b(l).name);
%XXXXXXXXXXXXXX
end
end
end
end
Please help me.
Thanks,
Kiran.
Hi,

Please tell me a way to extract a fixed size square ROI from an Image.

Thanks,
Kiran.
ImageAnalyst
2010-11-27 14:43:52 UTC
Permalink
subImage = fullImage(row1:row2, column1:column2);
Vivek
2011-01-11 06:27:04 UTC
Permalink
@Image Analyst,

now when it comes to ROI extraction, i used the code[mmROI.m] found from the below forum which of great deal to me. All the values are quite useful as well.
http://www.mathworks.com/matlabcentral/fileexchange/4511

how ever is it possible to extract the ROI part of the image and save as a different file??
the image is uploaded at
http://www.4shared.com/photo/EBcw8Doy/ROI.html

and the area highlighted in green is my ROI and i want to extract it and save as different image. what part of the code should be added/modified in mmROI.m?

-Vivek
ImageAnalyst
2011-01-11 11:10:11 UTC
Permalink
Post by Vivek
@Image Analyst,
now when it comes to ROI extraction, i used the code[mmROI.m] found from the below forum which of great deal to me. All the values are quite useful as well.http://www.mathworks.com/matlabcentral/fileexchange/4511
how ever is it possible to extract the ROI part of the image and save as a different file??
the image is uploaded athttp://www.4shared.com/photo/EBcw8Doy/ROI.html
and the area highlighted in green is my ROI and i want to extract it and save as different image. what part of the code should be added/modified in mmROI.m?
-Vivek
---------------------------------
Sure. If you know the coordinates of the region, just find the
bounding box and do what I said above:
subImage = fullImage(row1:row2, column1:column2);
Then call imwrite().
Vivek
2011-01-24 13:46:04 UTC
Permalink
how to find the co-ordinates of the highlighted region specifically in green? , the ROI is irregular shape that of the cancer.

or finding the co-ordinates is like using imtool command on the image, so that when we move the mouse on image, we could see the x,y coordinates.??

as u said,

subImage = fullImage(row1:row2, column1:column2);
Then call imwrite().

this is like using imcrop command right? , i need that ir-regular image exactly as the same as it looks in image bro. kindly specify what do i need to change the mmroi.m file?
ImageAnalyst
2011-01-24 14:24:24 UTC
Permalink
Vivek:
Perhaps you want to draw it freehand, like in my imfreehanddraw demo
below. Or maybe you want to find the green part using one of my color
detection demos at
http://www.mathworks.com/matlabcentral/fileexchange/authors/31862
and then once you've found the green part, extract the pixels inside
it, again using my demo below.
Good luck,
ImageAnalyst

% Demo to have the user freehand draw an irregular shape over
% a gray scale image, have it extract only that part to a new image,
% and to calculate the mean intensity value of the image within that
shape.
% By ImageAnalyst
%
% IMPORTANT: The newsreader may break long lines into multiple lines.
% Be sure to join any long lines that got split into multiple single
lines.
% These can be found by the red lines on the left side of your
% text editor, which indicate syntax errors, or else just run the
% code and it will stop at the split lines with an error.

% Change the current folder to the folder of this m-file.
if(~isdeployed)
cd(fileparts(which(mfilename)));
end
clc; % Clear command window.
clear; % Delete all variables.
close all; % Close all figure windows except those created by imtool.
imtool close all; % Close all figure windows created by imtool.
workspace; % Make sure the workspace panel is showing.
fontSize = 16;

% Read in standard MATLAB gray scale demo image.
grayImage = imread('cameraman.tif');
subplot(2, 3, 1);
imshow(grayImage, []);
title('Original Grayscale Image', 'FontSize', fontSize);
set(gcf, 'Position', get(0,'Screensize')); % Maximize figure.
message = sprintf('Left click and hold to begin drawing.\nSimply lift
the mouse button to finish');
uiwait(msgbox(message));
hFH = imfreehand();

% Create a binary image ("mask") from the ROI object.
binaryImage = hFH.createMask();
% Display the freehand mask.
subplot(2, 3, 2);
imshow(binaryImage);
title('Binary mask of the region', 'FontSize', fontSize);

% Calculate the area, in pixels, that they drew.
numberOfPixels1 = sum(binaryImage(:))
% Another way to calculate it that takes fractional pixels into
account.
numberOfPixels2 = bwarea(binaryImage)

% Get coordinates of the boundary of the freehand drawn region.
structBoundaries = bwboundaries(binaryImage);
xy=structBoundaries{1}; % Get n by 2 array of x,y coordinates.
x = xy(:, 2); % Columns.
y = xy(:, 1); % Rows.
subplot(2, 3, 1); % Plot over original image.
hold on; % Don't blow away the image.
plot(x, y, 'LineWidth', 2);

% Burn line into image by setting it to 255 wherever the mask is true.
burnedImage = grayImage;
burnedImage(binaryImage) = 255;
% Display the image with the mask "burned in."
subplot(2, 3, 3);
imshow(burnedImage);
caption = sprintf('New image with\nmask burned into image');
title(caption, 'FontSize', fontSize);
% Mask the image and display it.
% Will keep only the part of the image that's inside the mask, zero
outside mask.
blackMaskedImage = grayImage;
blackMaskedImage(~binaryImage) = 0;
subplot(2, 3, 4);
imshow(blackMaskedImage);
title('Masked Outside Region', 'FontSize', fontSize);
% Calculate the mean
meanGL = mean(blackMaskedImage(binaryImage));
% Report results.
message = sprintf('Mean value within drawn area = %.3f\nNumber of
pixels = %d\nArea in pixels = %.2f', ...
meanGL, numberOfPixels1, numberOfPixels2);
msgbox(message);

% Now do the same but blacken inside the region.
insideMasked = grayImage;
insideMasked(binaryImage) = 0;
subplot(2, 3, 5);
imshow(insideMasked);
title('Masked Inside Region', 'FontSize', fontSize);

% Now crop the image.
topLine = min(x);
bottomLine = max(x);
leftColumn = min(y);
rightColumn = max(y);
width = bottomLine - topLine + 1;
height = rightColumn - leftColumn + 1;
croppedImage = imcrop(blackMaskedImage, [topLine, leftColumn, width,
height]);
% Display cropped image.
subplot(2, 3, 6);
imshow(croppedImage);
title('Cropped Image', 'FontSize', fontSize);
Vivek
2011-01-24 16:07:03 UTC
Permalink
Sir ,
Its not related to hand drawing or selecting colors to be precise.
i'm using the following code which calculates area within the ROI, this part has been already done .

link for the code,
http://www.4shared.com/file/BlqOPDgt/mmROI.html

now when i run the code without changing for the image located at http://www.4shared.com/photo/CSIkXbpv/16normal.html

i could select the ROI in the form of blue colored control points like shown below, http://www.4shared.com/photo/Ux-N0u2f/ROI_Input.html

These blue color control points [the ROI] are saved to workspace and area within the polygon is calculated and written to a separate file.

Now all i need is that , i need to save the blue polygon which is basically the ROI as separate image.

-Vivek
ImageAnalyst
2011-01-27 18:34:07 UTC
Permalink
Post by Vivek
These blue color control points [the ROI] are saved to workspace and area within the polygon is calculated and written to a separate file.
Now all i need is that , i need to save the blue polygon which is basically the ROI as separate image.
-Vivek
=======================================
I would save the polygon coordinates with the save() function if you
want to save them to a disk file.
Vivek
2011-01-27 18:51:03 UTC
Permalink
that would be great , are you modifying the mmROI.m file?
i want that polygon as separate image sir.

-vivek
ImageAnalyst
2011-01-27 19:47:47 UTC
Permalink
Post by Vivek
that would be great , are you modifying the mmROI.m file?
i want that polygon as separate image sir.
-vivek
---------------------------------------
No, that would be your job. Why is calling the save() function so
difficult that you need me to tell you how to call it?
Vivek
2011-01-27 20:56:04 UTC
Permalink
Sir,
got it! great work!
Please do answer this thread as well
http://www.mathworks.com/matlabcentral/newsreader/view_thread/301635#814990

-Vivek
Vivek
2011-01-29 12:31:05 UTC
Permalink
Sir,
if you run the mmRoi.m file, it will ask for the input image and ROI selection control points. after the cntrl points are selected, the area is being calculated and written in to a text file.

Now the area of ROI is coming in decimal values....
but i want the values of ROI in pixelcount, please help me.
ImageAnalyst
2011-01-29 19:57:44 UTC
Permalink
Post by Vivek
Sir,
if you run the mmRoi.m file, it will ask for the input image and ROI selection control points. after the cntrl points are selected, the area is being calculated and written in to a text file.
Now the area of ROI is coming in decimal values....
but i want the values of ROI in pixelcount, please help me.
----------------------------------------------------------------------

Use floor(), ceil(), round(), or int32() - whatever you need to to get
your numbers as integers.
Vivek
2011-01-30 05:26:03 UTC
Permalink
Post by ImageAnalyst
Use floor(), ceil(), round(), or int32() - whatever you need to to get
your numbers as integers.
i want the values in Pixels sir, not as interger. the integer value is written into file as, ROIarea , but instead i want the pixel count values in Roi area.
ImageAnalyst
2011-01-30 23:45:31 UTC
Permalink
Post by Vivek
Post by ImageAnalyst
Use floor(), ceil(), round(), or int32() - whatever you need to to get
your numbers as integers.
i want the values in Pixels sir, not as interger. the integer value is written into file as, ROIarea , but instead i want the pixel count values in Roi area.
------------------------------------------------
Vivek:
I don't know what mmROI is. Show your code. 2D arrays can be
considered as images, and if so, their array values are "pixel"
values. They may or may not be integers. Coordinates can be gotten
in a variety of ways, such as via roipoly(), and may or may not be
integers. Why don't you post an image and your code and say what you
want to measure. I'm not sure which subject we're talking about
anymore - please don't mix or refer to other threads in a confusing
way. If you're talking about that image with a green polygon on it,
then you must have code where the user called roipoly or similar.
Post your original image (without the green polygon burned into it),
and all the code you have to have the user draw that polygon. I
already gave you code for drawing and getting areas and if that
doesn't work or do the same thing then I need to know why. Make sure
you have a comment before every line so I know what you're doing, as
well as just being good programming practice in general.
ImageAnalyst
Vivek
2011-01-31 14:07:04 UTC
Permalink
image with out green polygon
http://www.4shared.com/photo/CSIkXbpv/16normal.html

now , i'm giving the code, which calculates the area of ROI on an image and writes to a different text file. the unnecessary functions of the code are already removed.

Here are some of the changes i need to do.

1) first and foremost, area of ROI is coming in decimal values, which i want to convert to pixels.

2) secondly, ROI center (X,Y) which is also coming in decimals, which there should not be decimals.

3) now ROI for which the area is calculated is not saved as separate image,but i wish to do so.

*******************SOURCE CODE**************************************
sir, the code may be broken into multiple lines , please do check it.
or

the link for the code [textfile] is
http://www.4shared.com/document/2RsvKo7H/mmROI.html


function [roi, im] = mmROI
% 1) Goal: Interactively process MULTIPLE images with MULTIPLE ROIs
% (so-called mmROI), which returns ROI mean, std, min, max, median, area
% and center(X,Y), and plots the mean/std values along the image series.
%
% 2) Usage: [roi, im] = mmROI; (please don't forget to add a semicolon ";"
% at the end of this command. Otherwise, all image data will be showing on
% screen!)
% a) The statistic data are in roi structures, which may be save into a
% text file (optional). If you want to see the details, you may type,
% for example, roi.mean to show all mean values; roi.mean(1, 1, 1)
% to display the mean value of the 1st image, the 1st ROI and the red
% color; roi.std(3, 1, :) to show std values of all image 1, the 1st
% ROI and the blue color, etc.
% b) The image data are in a stack (im). You may use immovie(im) to play
% a movie or montage(im) to show all images in one figure.
%
% 3) Limitation: all images MUST have exactly identical size. Otherwise, an
% error will take place and the program will be terminated. The reason is
% that all image data were loaded into a stack matrix, im(:,:,:,imNumber).
%
% 4)The mostimportant feature of this new mmROI is that%it permits to open
% multiple images and to process multiple ROIs interactively.
%I believe that it is much more valuable to those who are interested in
%studying the dynamic phenomenon via the image techniques.
%
% 5) The multiple file opening is based on javax.swing.JFileChooser, so
% this mmROI program should work for matlab with jave version 1.3.1 or
% newer (although it was created on Matlab, v6.5.1, R13SP1). If it dose not
% work for an older version of matlab, you may download "uigetfiles.dll"
% (mathworks file exchange ID: 331) into your matlab directory, and
% substitute those codes in charge of file opening as stated in the
% program.
%
% 8) An input dialog box will pop up, asking you to input the total number
% of ROIs (default value 1), and to select a working image (Figure No. XX)
% in which you are going to draw your ROIs (default is set to the 1st
% image). These ROIs will be applied to all images opened. Some users may
% want to draw different ROIS in each images, you may easily modify the
% program by yourself (If you need help, you may contact me).
%
% 7) ROI selection is based upon ROIPOLY, therefore, image process toolbox
% is needed. Use normal button clicks to add vertices to the polygon.
% Pressing <BACKSPACE> or <DELETE> removes the previously selected vertex.
% A shift-click, right-click, or double-click adds a final vertex to the
% selection and then starts the fill; pressing <RETURN> finishes the
% selection without adding a vertex. For more details, please see HELP
% ROIPOLY.
%
% 8) ROI statistic data were calculated by using IMPIXEL, please see HELP
% IMPIXEL if necessary. If you don't have IMPIXEL in your image process
% toolbox, you may modified the corresponding codes according to my
% previous program ROI.m (Mathwork file exchange ID: 4462).
%
% 9) ROI coordinates were automatically saved into a text file in your
% current directory ("roiXY.txt"). I think this maybe be needed if you want
% to process further the images with exactly identical ROI polygon, such as
% poly2mask, etc. If you want to keep it, please find roiXY.txt, and backup
% before performing any new mmROI. Otherwise, it will be overwriten.
%

% Multiple file selections based upon javax.swing.JFileChooser
import com.mathworks.mwswing.MJFileChooser;
import com.mathworks.toolbox.images.ImformatsFileFilter;

filechooser = javax.swing.JFileChooser(pwd);
filechooser.setMultiSelectionEnabled(true);
filechooser.setFileSelectionMode(filechooser.FILES_ONLY);

% Parse formats from IMFORMATS
formats = imformats;
nformats = length(formats);
desc = cell(nformats,1);
[desc{:}] = deal(formats.description);
ext = cell(nformats,1);
[ext{:}] = deal(formats.ext);

% Create a filter that includes all extensions
ext_all = cell(0);
for i = 1:nformats
ext_i = ext{i};
ext_all(end+1: end+numel(ext_i)) = ext_i(:);
end

[ext{end+1,1}] = ext_all;
[desc{end+1,1}] = 'All image files';

% Make a vector of String arrays
extVector = java.util.Vector(nformats);
for i = 1:nformats+1
extVector.add(i-1,ext{i})
end

% Push formats into ImformatsFileFilter so instances of
% ImformatsFileFilter will be based on IMFORMATS.
ImformatsFileFilter.initializeFormats(nformats,desc,extVector);

% Create all_images_filter
all_images_filter = ...
ImformatsFileFilter(ImformatsFileFilter.ACCEPT_ALL_IMFORMATS);
filechooser.addChoosableFileFilter(all_images_filter);

% Add one ChoosableFileFilter for each format in IMFORMATS
for i = 1:nformats
filechooser.addChoosableFileFilter(ImformatsFileFilter(i-1))
end

% Put accept all files at end
accept_all_filter = filechooser.getAcceptAllFileFilter;
filechooser.removeChoosableFileFilter(accept_all_filter);
filechooser.addChoosableFileFilter(accept_all_filter);

% Make default be all_images_filter
filechooser.setFileFilter(all_images_filter);
returnVal = filechooser.showOpenDialog(com.mathworks.mwswing.MJFrame);


if (returnVal == MJFileChooser.APPROVE_OPTION)
pathname = [char(filechooser.getCurrentDirectory.getPath), ...
java.io.File.separatorChar];
selectedfiles = filechooser.getSelectedFiles;
imNumber = size(selectedfiles);
for n = 1:imNumber
filenames(n) = selectedfiles(n).getName;
end
filenames = char(filenames);
else
pathname = pwd;
filenames = 0;
end

if filenames == 0;
return;
end

for imIndex = 1:imNumber
im(:,:,:,imIndex) = imread([pathname, filenames(imIndex,:)]);
figure;
imHandle = imshow(im(:,:,:,imIndex));
title(filenames(imIndex,:));
axis image;
axis off;
end

prompt = {'Total ROI Number:', 'Perform ROI selection on which image (Figure No. XX):'};
dlg_title = 'Inputs for mmROI function';
num_lines = 1;
def = {'1','1'};
inputs = str2num(char(inputdlg(prompt, dlg_title, num_lines, def)));

roiNumber = inputs(1);
workingImage = inputs(2);

% generate a jet colormap according to roiNumber
clrMap = jet(roiNumber);
rndprm = randperm(roiNumber);

hold on;

tfid = fopen('roiXY.txt', 'w+');

for roiIndex = 1:roiNumber
figure(workingImage);
[x, y, BW, xi, yi] = roipoly;
xmingrid = max(x(1), floor(min(xi)));
xmaxgrid = min(x(2), ceil(max(xi)));
ymingrid = max(y(1), floor(min(yi)));
ymaxgrid = min(y(2), ceil(max(yi)));
xgrid = xmingrid : xmaxgrid;
ygrid = ymingrid : ymaxgrid;
[X, Y] = meshgrid(xgrid, ygrid);
inPolygon = inpolygon(X, Y, xi, yi);
Xin = X(inPolygon);
Yin = Y(inPolygon);

% Save each roi coordinates into a text file "roiXY.txt", so that one
% can easily use "poly2mask" for further regional image process with
% exactly identical ROIs created here.
fprintf(tfid, 'ROI "%s":\n', num2str(roiIndex));
fprintf(tfid, 'Xi = \t');
fprintf(tfid, '%10.2f\t', xi);
fprintf(tfid, '\n');
fprintf(tfid, 'Yi = \t');
fprintf(tfid, '%10.2f\t', yi);
fprintf(tfid, '\n');

roi.area(:,roiIndex) = polyarea(xi,yi);
roi.center(:,roiIndex) = [mean(Xin(:)), mean(Yin(:))];

for imIndex = 1:imNumber
roi.mean(:,roiIndex,imIndex) = mean(impixel(x,y,im(:,:,:,imIndex),xi,yi));
roi.std(:,roiIndex,imIndex) = std(impixel(x,y,im(:,:,:,imIndex),xi,yi));
roi.min(:,roiIndex,imIndex) = min(impixel(x,y,im(:,:,:,imIndex),xi,yi));
roi.max(:,roiIndex,imIndex) = max(impixel(x,y,im(:,:,:,imIndex),xi,yi));
roi.median(:,roiIndex,imIndex) = median(impixel(x,y,im(:,:,:,imIndex),xi,yi));

figure(imIndex);
hold on;
plot(xi,yi,'Color',clrMap(rndprm(roiIndex), :),'LineWidth',1);
text(roi.center(1,roiIndex), roi.center(2,roiIndex), num2str(roiIndex),...
'Color', clrMap(rndprm(roiIndex), :), 'FontWeight','Bold');
end
end

fclose(tfid);

% Save ROIs to a file (optional)
SaveOutput = questdlg('Do you want to save ROI outputs ?');
switch SaveOutput
case 'Yes'
[outFilename, outPathname] = uiputfile('*.txt', 'Please select an output file');
if outFilename == 0
disp(' Cancel by user !');
else
ofid = fopen([outPathname outFilename], 'w+');
fprintf(ofid, '%-20s\t %-25s\n', 'Date\time = ', datestr(now));
fprintf(ofid, '\n');
fprintf(ofid, 'Images used in this ROI process: \n');
fprintf(ofid, '\t"%s"\n', pathname(1,:));
fprintf(ofid, ' Index\t\tfilenames \n');
for imIndex = 1:1:imNumber
fprintf(ofid, '%10.0f\t\t', imIndex);
fprintf(ofid, '%-100s\n', filenames(imIndex,:));
end
end
otherwise
outFilename = 0;
end

warning off MATLAB:colon:operandsNotRealScalar;
imIndex = 1:imNumber;

% Plot of mean/std values along the image series. Each ROI plots as a new
% figure with three lines of red, green and blue, respectively.
for roiIndex=1:roiNumber
% write ROI statistics into file (optional)
if outFilename ~= 0
fprintf(ofid, '\n');
fprintf(ofid, 'ROI "%s" statistic data: \n\n', num2str(roiIndex));

fprintf(ofid, '%20s\t', 'ROI Area = ');
fprintf(ofid, '%10.2f\t', roi.area(:,roiIndex));
fprintf(ofid, '\n');

fprintf(ofid, '%20s\t', 'ROI center (X,Y) = ');
fprintf(ofid, '%10.2f\t', roi.center(:,roiIndex));
fprintf(ofid, '\n\n');

fprintf(ofid, '%20s\t', 'Image Index = ');
fprintf(ofid, '%10.0f\t', imIndex);
fprintf(ofid, '\n\n');

end
end

if outFilename ~= 0
disp(sprintf('Done! ROI statistic data were output to "%s",', outFilename));
disp('ROI coordinates (X,Y) were saved in "roiXY.txt",');
disp('but the images were not saved yet!');
fclose(ofid);
else
disp('Done, ROI coordinates (X,Y) were saved in "roiXY.txt",');
disp('but their statistics and the images were not saved!');
end

% end of code
Nivetha Chezhian
2017-03-14 06:15:03 UTC
Permalink
Post by ImageAnalyst
subImage = fullImage(row1:row2, column1:column2);
hi, is it possible to extract the ROI automatically without manually specifying the coordinates / without using free hand selection.If so please mention any function for the same.
r***@gmail.com
2014-08-30 04:08:30 UTC
Permalink
i want to generate sequences of image by inducing motion in matlab code please help me
Loading...