MATLAB: Extraction of the region of interest in MATLAB

extraction of the roiimage segmentation

I have this binary image as my input and I want to extract the region marked in red automatically without manually providing any coordinates Any help will be appreciated

Best Answer

Here is some code which should work for this task:
Read in the image:
Image=imread('input.bmp');
figure
imshow(Image)
Get the red and green channel of the rgb-image:
RedChannel=Image(:,:,1);
GreenChannel=Image(:,:,2);
Convert red areas to 1 and others to 0:
Image_BW = (RedChannel>200).* (GreenChannel<100);
figure(1)
clf
imshow(Image_BW)
Get the boundaries:
B=bwboundaries(Image_BW);
Get and plot inner boundary
Bound=B{2};
hold on
plot(Bound(:,2),Bound(:,1),'g-')
Get minimal and maximal x-position of roi
min_x=min(Bound(:,2));
max_x=max(Bound(:,2));
Image2=zeros(size(Image));
%loop over columns intersecting roi
for i=min_x:max_x
%get logical vector with 1s for roi-boundary-pixels in ith line
x=Bound(:,2)==i;
%get minimal and maximal y-value of roi in ith column
min_y=min(Bound(x,1));
max_y=max(Bound(x,1));
%write ith column of roi to Image2
Image2(min_y:max_y,i,:)=Image(min_y:max_y,i,:);
end
Plot the result
figure(2)
imshow(Image2);