function [J,type] = image_type_convert(I,newtype,thr)
% Detect and convert the image to one out of four types: BW, LABELED, CONTOUR,
% LIKELIHOOD.
%% Detection of image type
L = numel(unique(I(:))); % number of unique gray levels
if L<=2 % binary image ==> BW or CONTOUR
F = filter2([1 1 1;1 1 1;1 1 1]/9,I,'same');
if max(F(:))<=5/9 % cross is the worst case for EDGE
type = 'EDGE';
else
type = 'CONTOUR';
end
else % LABELED or LIKELIHOOD
numofblobs=length(regionprops(bwlabel(I>0),'Area'));
if max(I(:))==numofblobs && min(I(:))==0
type = 'LABELED';
else
type = 'BW';
end
end
%% Convert the types
switch newtype
case 'BW'
switch type
case 'BW'
J=I;
case 'CONTOUR'
J=imfill(I,'holes');
case 'LABELED'
J=I>0;
case 'LIKELIHOOD'
J=I>thr;
end
case 'CONTOUR'
switch type
case 'BW'
J=bwmorph(I,'remove');
case 'CONTOUR'
J=I;
case 'LABELED'
J=bwmorph(I,'remove');
case 'LIKELIHOOD'
J=bwmorph(I>thr,'remove');
end
case 'LABELED'
switch type
case 'BW'
J=bwlabel(I);
case 'CONTOUR'
J=bwlabel(imfill(I,'holes'));
case 'LABELED'
J=I;
case 'LIKELIHOOD'
J=bwlabel(I>thr);
end
case 'LIKELIHOOD'
switch type
case 'BW'
J=bwdist(~I);
case 'CONTOUR'
J=bwdist(~imfill(I,'holes'));
case 'LABELED'
J=bwdist(~(I>0));
case 'LIKELIHOOD'
J=I;
end
end