www.pudn.com > insect_seg.rar > insect_seg.m
clear all
close all
[filename, pathname] = uigetfile({'*.JPG';'*.BMP'},'Pick one file');
tic;
I=imread([pathname,filename]);
J=rgb2gray(I);
figure(1);
imshow(J)
J=imadjust(J);
BWs = edge(J, 'sobel', (graythresh(J) * .03));
figure(2);
imshow(BWs)
se90 = strel('line', 3, 90);
se0 = strel('line', 3, 0);
BWsdil = imdilate(BWs, [se90 se0]);
figure(3), imshow(BWsdil), title('dilated gradient mask');
BWdfill = imfill(BWsdil, 'holes');
figure(4);
imshow(BWdfill);
BWnobord = imclearborder(BWdfill, 4);
figure(5);
imshow(BWnobord), title('cleared border image');
seD = strel('diamond',1);
BWfinal = imerode(BWnobord,seD);
BWfinal = imerode(BWfinal,seD);
BWfinal(1,:)=0;
BWfinal(:,1)=0;
BWfinal(480,:)=0;
BWfinal(:,640)=0;
[BWfinal,num]=bwlabel(BWfinal,8);
BWfinal=bwareaopen(BWfinal,800);
figure(6);
imshow(BWfinal), title('segmented image');
segmentedR = I(:,:,1);
segmentedG = I(:,:,2);
segmentedB = I(:,:,3);
segmentedR (find(BWfinal==0))=0;
segmentedG (find(BWfinal==0))=255;
segmentedB (find(BWfinal==0))=0;
segmented (:,:,1) = segmentedR;
segmented (:,:,2) = segmentedG;
segmented (:,:,3) = segmentedB;
figure(7);
imshow(segmented)
bugRotationAngle = estimateBugOrientation(BWfinal,8);
doBugRotationAngleThreshold = 0;
[R ang] = rotateBug(BWfinal,bugRotationAngle,doBugRotationAngleThreshold);
imwrite(R, [pathname filename '.binary.TIFF'],'Compression','none'); % save segmented image
[RI ang] = rotateBug(I,bugRotationAngle,doBugRotationAngleThreshold);
imwrite(RI, [pathname filename '.rotated.TIFF'],'Compression','none'); % save rotated image
BW = R;
J=RI;
L = find(BW == 0);
A = J(:,:,1);
B = J(:,:,2);
C = J(:,:,3);
A(find(BW==0)) = 0;
B(find(BW==0)) = 200;
C(find(BW==0)) = 0;
J(:,:,1) = A;
J(:,:, 2) = B;
J(:,:, 3) = C;
imwrite(J, [pathname filename '.segmented.TIFF'],'Compression', 'none');
figure(9)
imshow(J);
[B,L,N,A] = bwboundaries(BW);
figure(10)
imshow(BW); hold on;
for k=1:length(B),
if(~sum(A(k,:)))
boundary = B{k};
plot(boundary(:,2), boundary(:,1), 'r','LineWidth',4);
for l=find(A(:,k))',
boundary = B{l};
plot(boundary(:,2), boundary(:,1), 'g','LineWidth',4);
end
end
end
maskForAlphaMatting = generateAMMask(BW,2);
imwrite(maskForAlphaMatting, [pathname filename '.finalMask.TIF'],'Compression','none');
toc;
t=toc