%%%%%%%%%%%%%%%%%
% maximum of connected area
%%%%%%%%%%%%%%%%%
%Load picture
clear all;
x=imread('Lena.bmp');
%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Note: you should add your own denoise code here
%%%%%%%%%%%%%%%%%%%%%%%%%%%
I=rgb2gray(x);
imshow(I);
se=strel('square',5);
gd=imdilate(I,se);
ge=imerode(I,se);
m_grad=imsubtract(gd,ge);
M=imfill(m_grad,'holes');
se1=strel('square',5);
fo=imopen(M,se1);
foc=imclose(fo,se1);
figure,imshow(foc);
im=foc;
% m=3;n=5;
% th=zbthresh(m,n,im);
BW=im2bw(im,0.4);
% ............
% ............
%Locate rectangle
L = bwlabel(BW,8); % Label connected components
BB = regionprops(L, 'BoundingBox'); % Get objects in bounding box
%convert into matrix
BB1=struct2cell(BB);
BB2=cell2mat(BB1);
[s1 s2]=size(BB2);
mx=0;
% select the maximum connected area
for k=3:4:s2-1
p=BB2(1,k)*BB2(1,k+1);
if p>mx & (BB2(1,k)/BB2(1,k+1))<1.8
mx=p;
j=k;
end
end
%convert itno multi-colored picture coordinates
xx = floor(BB2(1,j-2)) ;
yy = floor(BB2(1,j-1));
ww = floor(BB2(1,j)) ;
hh = floor(BB2(1,j+1)) ;
% extract sub-picture matrix
subx = x(yy:yy+hh,xx:xx+ww, :); % x is multi-colored picture
%Show result
figure,imshow(subx);
pause(30); % pause for 3 seconds
close all;
% save jpg to file
imwrite(subx,'mca.jpg');