all the characters in number plate are not recognized - matlab

I am extracting and segmenting the characters from number plate.I am facing problems with character recognition. I wish to extract the number and symbol and do not consider about alphabets.I am getting one character as output out of eight. After running this code, i got answer is'1'. I am appending matlab code for location and segmentation of the plate. I have given the input image for the reference.`]5 []6[]7[]8Can anyone help me to rectify this error?
function [ImgPlate] = LocationPlate(I)
%% Cutting and resizing the original image %%
% I=imread('2222.jpg');
% figure,imshow(I);
[rows columns]=size(I);
columns=columns/3;
xmin=round(0.20*rows);
ymin=round(0.20*columns);
width=round((0.85*columns)-(0.10*columns));
height=round((0.85*rows)-(0.15*rows));
Io=imcrop(I,[xmin ymin width height]);
Io=imresize(Io,[480 640]);
Io=rgb2gray(Io);
Io=imadjust(Io);
%% Image processing to focus the area of number plate %%
%% Smooth edges and contours to delete characters.
se=strel('rectangle',[6 30]);
Ic=imclose(Io,se);
Ic=imadjust(Ic);
tophat=Ic-Io;
Ibw=(tophat>85);
%% Remove the related elements with fewer than 70 pixels %%
%% Remove objects that are not plate %%
plate= bwlabel(Ibw,4);
obj= max(max(plate));
dim1 = regionprops(plate, 'area')';
dim=[dim1.Area];
dim(find(dim<70))=0;
for i=1:obj
index=find(plate==i);
if dim(i)==0
plate(index)=0;
else
plate(index)=1;
end
end
CC=bwconncomp(plate);
P=regionprops(CC,'all');
[rp cp]=size(plate);
for i=1:CC.NumObjects
if P(i).MajorAxisLength>(2*cp/3)
plate(P(i).PixelIdxList(:,1))=0;
end
end
%% Remove objects that are not candidates for plate %%
se3=strel('rectangle',[30 70]);
r2=imclose(plate,se3);
se2=strel('rectangle',[5 30]);
r=imdilate(r2,se2);
CC=bwconncomp(r);
P=regionprops(CC,'all');
for i=1:CC.NumObjects
if P(i).MajorAxisLength>(2*cp/3)
r(P(i).PixelIdxList(:,1))=0;
end
end
%% select the largest connected component after preprocessing, the
%%plate
plate1= bwlabel(r,4);
dim2= regionprops(plate1, 'area')';
dim1=[dim2.Area];
f=max(dim1);
indMax=find(dim1==f);
plate1(find(plate1~=indMax))=0;
%% cutting of original image %%
[cuty, cutx] = find( plate1 > 0);
up = min(cuty);
down = max(cuty);
left = min(cutx);
right = max(cutx);
img_cut_v = Io(up:down,:,:);
img_cut_h = img_cut_v(:,left:right,:);
ImgPlate = img_cut_h;
%% different mask for location plate %%
[r c]=size(ImgPlate);
if r<25 || r>65
[rows columns]=size(I);
columns=columns/3;
xmin=round(0.20*rows);
ymin=round(0.20*columns);
width=round((0.85*columns)-(0.10*columns));
height=round((0.85*rows)-(0.15*rows));
Io=imcrop(I,[xmin ymin width height]);
Io=imresize(Io,[480 640]);
Io=rgb2gray(Io);
Io=imadjust(Io);
se=strel('rectangle',[6 30]);
Ic=imclose(Io,se);
Ic=imadjust(Ic);
tophat=Ic-Io;
Ibw1=(tophat>85);
mask=zeros(480,640);
for i=40:370
for j=40:575
mask(i,j)=1;
end
end
Ibw=Ibw1 & im2bw(mask);
plate= bwlabel(Ibw,4);
obj= max(max(plate));
dim1 = regionprops(plate, 'area')';
dim=[dim1.Area];
dim(find(dim<70))=0;
for i=1:obj
index=find(plate==i);
if dim(i)==0
plate(index)=0;
else
plate(index)=1;
end
end
CC=bwconncomp(plate);
P=regionprops(CC,'all');
[rp cp]=size(plate);
for i=1:CC.NumObjects
if P(i).MajorAxisLength>(cp/3)
plate(P(i).PixelIdxList(:,1))=0;
end
end
se3=strel('rectangle',[30 70])
r2=imclose(plate,se3);
se2=strel('rectangle',[5 30]);
r=imdilate(r2,se2);
plate1= bwlabel(r,4);
dim2= regionprops(plate1, 'area')';
dim1=[dim2.Area];
f=max(dim1);
indMax=find(dim1==f);
plate1(find(plate1~=indMax))=0;
[cuty, cutx] = find( plate1 > 0);
up = min(cuty);
down = max(cuty);
left = min(cutx);
right = max(cutx);
img_cut_v = Io(up:down,:,:);
img_cut_h = img_cut_v(:,left:right,:);
ImgPlate = img_cut_h;
end
%% Representation %%
% figure(1);
% imshow(I);
% subplot(2,2,1);imshow(I);
% subplot(2,2,2);imshow(Ic);% subplot(2,2,3);imshow(plate);
% subplot(2,2,4);imshow(plate1);
figure(2); imshow(img_cut_h);title('output location plate');
end
function [Objects,ImgChar]=Segmentation(ImgPlate)
%% Binarize the image %%
level = graythresh(ImgPlate);
Ibw =(im2bw(ImgPlate,level));
%% Select the orientation of the largest object in the image.
%% Turn this angle at the picture.
%% Plate cutting to segment the characters that compose %%
Fl=bwlabel(Ibw);
Statsbf=regionprops(Fl,'all');
Flmax=find([Statsbf.Area]==max([Statsbf.Area]));
angle=Statsbf(Flmax).Orientation;
F2=imrotate(Fl,-angle);
L=bwlabel(F2);
Statsbf=regionprops(L,'all');
maxi=find([Statsbf.Area]==max([Statsbf.Area]));
BB=Statsbf(maxi).BoundingBox;
F2=imcrop(F2,[BB(1,1) BB(1,2) BB(1,3) BB(1,4)]);
% figure,imshow(F2);
%% First three and last three rows to zero.
%% First two and last two columns to zero.
%% So remove connectivity between characters and background %%
%% Remove small impurities %%
L4=not(F2);
[r c]=size(L4);
L4(1,:)=0;
L4(2,:)=0;
L4(3,:)=0;
L4(r,:)=0;
L4(r-1,:)=0;
L4(r-2,:)=0;
L4(:,1)=0;
L4(:,2)=0;
L4(:,c)=0;
L4(:,c-1)=0;
L4b=bwlabel(L4);
Stats3=regionprops(L4b,'all');
sarea3=[Stats3.Area];
G=find(sarea3<70);
for cv=1:length(G)
G1=find(L4b==G(cv));
L4(G1)=0;
end
[r c]=size(L4);
CC=bwconncomp(L4);
L=bwlabel(L4);
ind2=max(L(:,c-2));
P=regionprops(CC,'all');
%% Remove objects smaller and larger than a character %%
i=1;
if (max(P(i,1).PixelList(:,1))-min(P(i,1).PixelList(:,1)))<(c/13)
L4(CC.PixelIdxList{1,i})=0;
end
for i=1:CC.NumObjects
if (max(P(i,1).PixelList(:,1))-min(P(i,1).PixelList(:,1)))>(2*c/3)
L4(CC.PixelIdxList{1,i})=0;
end
if (max(P(i,1).PixelList(:,2))-min(P(i,1).PixelList(:,2)))<(r/3)
L4(CC.PixelIdxList{1,i})=0;
end
if (max(P(i,1).PixelList(:,1))-min(P(i,1).PixelList(:,1)))<(c/8)
L4(find(L==ind2))=0;
end
end
L4=imclose(L4,strel('disk',1));
L4=imopen(L4,strel('disk',1));
% figure(4);
imshow(L4);
L4b=bwlabel(L4);
Stats3b=regionprops(L4b,'all');
N=length(Stats3b);
while N>8
L4=imdilate(L4,strel('disk',1));
L4b=bwlabel(L4);
Stats3b=regionprops(L4b,'all');
N=length(Stats3b);
end
L4b=bwlabel(L4);
Stats3b=regionprops(L4b,'all');
ImgChar=zeros(100,100,N);
%% Dividing characters which are connected %%
%% Remove objects that have been listed as characters but are not%
%% Show every character in the correct position %%
cont=0;
cont1=0;
for i=1:N
[r1 c1]=size(Stats3b(i,1).Image);
if c1>round(c/6)
cont1=cont;
Stats3b(i,1).Image(:,round(c1/2))=0;
L5=Stats3b(i,1).Image;
CC=bwconncomp(L5);
CC1=regionprops(CC,'all');
for j=1:CC.NumObjects
[r2 c2]=size(CC1(j,1).Image);
if c2>round(c/7)
CC1(j,1).Image(:,round(c2/2))=0;
L6=CC1(j,1).Image;
LL=bwconncomp(L6);
CC2=regionprops(LL,'all');
for k=1:LL.NumObjects
CC2(k).Image=imresize(CC2(k).Image, [100 100]);
figure;imshow((CC2(k).Image))
ImgChar(:,:,i+cont1)=not(CC2(k).Image);
cont1=cont1+1;
end
cont=cont+1;
else
CC1(j).Image=imresize(CC1(j).Image, [100 100]);
figure;imshow((CC1(j).Image))
ImgChar(:,:,i+cont1)=not(CC1(j).Image);
cont1=cont1+1;
end
end
cont=cont+1;
else
Stats3b(i).Image=imresize(Stats3b(i).Image, [100 100]);
figure;imshow((Stats3b(i).Image));
if cont~=0
ImgChar(:,:,i+cont)=not(Stats3b(i).Image);
else
ImgChar(:,:,i)=not(Stats3b(i).Image);
end
end
end
%% Remove spurious %%
[x, y, Objects]=size(ImgChar);
end
function [strPlate] = Recognition(I)
I=imread('2222.jpg');
[ImgPlate] = LocationPlate(I);
[Objects,ImgChar]=Segmentation(ImgPlate);
N=struct('Image',{});
numbers={'0','1','2','3','4','5','sign'};
N(1).Image=imresize(im2bw(uint8(imread('untitled0.bmp'))),[100 100]);
N(2).Image=imresize(im2bw(uint8(imread('untitled1.bmp'))),[100 100]);
N(3).Image=imresize(im2bw(uint8(imread('untitled2.bmp'))),[100 100]);
N(4).Image=imresize(im2bw(uint8(imread('untitled3.bmp'))),[100 100]);
N(5).Image=imresize(im2bw(uint8(imread('untitled4.bmp'))),[100 100]);
N(6).Image=imresize(im2bw(uint8(imread('untitled5.bmp'))),[100 100]);
N(7).Image=imresize(im2bw(uint8(imread('sign.jpg'))),[100 100]);
if Objects==8
strPlate=[];
for i=1:Objects
char=ImgChar(:,:,i);
if (i==2)||(i==3)||(i==4) || (i==5) || (i==6)||(i==7) ||(i==8)
list_corr=[];
for j=1:7
corr=corr2(N(j).Image,char);
list_corr=[list_corr corr];
end
f=max(list_corr);
maxcorr=find(list_corr==f);
strPlate=[strPlate numbers(maxcorr)];
end
end
end
end

I find you compare char image with the default value of ImgChar (zeros). I discovered this by add imshow(char) as you can see in the below code.
for i=1:Objects
char=ImgChar(:,:,i);
if (i==2)||(i==3)||(i==4) || (i==5) || (i==6)||(i==7) ||(i==8)
list_corr=[];
for j=1:6
corr=corr2(N(j).Image,char);
list_corr=[list_corr corr];
end
close all
figure;imshow(char)
f=max(list_corr);
maxcorr=find(list_corr==f);
strPlate=[strPlate numbers(maxcorr)];
end
end
To correct the above error, I modified the below code to store images in ImgChar. this line maybe not correct but I believe my answer may help you.
Stats3b(i).Image=imresize(Stats3b(i).Image, [100 100]);
figure;
imshow((Stats3b(i).Image));
ImgChar(:,:,i) = Stats3b(i).Image;% added
if cont~=0
else
ImgChar(:,:,i)=not(Stats3b(i).Image);
end

Related

how to preallocate the variable in matlab code?

while implementing kernel based grapg cut method, I am getting error at line: area(1+1)=999999999;
suggestion for correcting the error is line 147: the variable 'area' appears to change size on every loop iteration(within a script).
Considering preallocation for speed, please suggest me how to preallocate the variable area,in the matlab code?
Code:
clear all; close all;
%%%%%%%%%%%%%%%%%%%%%%%Main inputs and parameters%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%Note: The RBF-kernel parameters are given in function kernel RBF.m%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%Example with a color image%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%path = 'Images\Color_image.jpg';
%im = im2double(imread(path));
%alpha=1; %The weight of the smoothness constraint
%k =8; %The number of regions
%%%%%%%Example with a SAR image corrupted with a multiplicative noise%%%%%%
%%%%%%%%%%%%%%%%Uncomment the following to run the example)%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
path = 'Images\Sar_image.tif';
im = im2double(imread(path));
alpha=0.6;
k =4;
%%%%%%%%%%%%%%%%%%%%%%%%%%Example with a brain image%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%Uncomment the following to run the example)%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%path = 'Images\Brain_image.tif';
%im = im2double(imread(path));
%alpha=0.1;
%k =4;
sz = size(im);
Hc=ones(sz(1:2));
Vc=Hc;
i_ground = 0; % rank of the bakground for plotting, 0: the darkest;
%k-1 the brightest; 99: nowhere
diff=10000;
an_energy=999999999;
iter=0;
iter_v=0;
energy_global_min=99999999;
distance = 'sqEuclidean'; % Feature space distance
% Initialization: cluster the data into k regions
tic,
disp('Start kmeans');
data = ToVector(im);
[idx c] = kmeans(data, k, 'distance', distance,'EmptyAction','drop','maxiter',100);
c=c(isfinite(c(:,1)),:);
k=size(c,1);
k_max=k;
kmean_time=toc;
Dc = zeros([sz(1:2) k],'single');
c;
tic
while iter < 5
iter=iter+1;
clear Dc
clear K
c;
for ci=1:k
K=kernel_RBF(im,c(ci,:));
Dc(:,:,ci)=1-K;
end
clear Sc
clear K
%% The smoothness term
Sc = alpha*(ones(k) - eye(k));
gch = GraphCut('open', Dc, Sc, Vc, Hc);
[gch L] = GraphCut('swap',gch);
[gch se de] = GraphCut('energy', gch);
nv_energy=se+de;
gch = GraphCut('close', gch);
if (nv_energy<=energy_global_min)
diff=abs(energy_global_min-nv_energy)/energy_global_min;
energy_global_min=nv_energy;
L_global_min=L;
k_max=k;
nv_energy;
iter_v=0;
% Calculate region Pl of label l
if size(im, 3)==3 % Color image
for l=0:k-1
Pl=find(L==l);
card=length(Pl);
K1=kernel_RBF(im(Pl),c(l+1,1));K2=kernel_RBF(im(Pl),c(l+1,2));K3=kernel_RBF(im(Pl),c(l+1,3));
smKI(1)=sum(im(Pl).*K1); smKI(2)=sum(im(Pl+prod(sz(1:2))).*K2); smKI(3)=sum(im(Pl+2*prod(sz(1:2))).*K3);
smK1=sum(K1);smK2=sum(K2);smK3=sum(K3);
if (card~=0)
c(l+1,1)=smKI(1)/smK1;c(l+1,2)=smKI(2)/smK2;c(l+1,3)=smKI(3)/smK3;
else
c(l+1,1)=999999999;c(l+1,2)=999999999;c(l+1,3)=999999999;
end
end
end
if size(im, 1)==1 % Gray-level image
for l=0:k-1
Pl=find(L==l);
card=length(Pl);
K=kernel_RBF(im(Pl),c(l+1,1));
smKI=sum(im(Pl).*K);
smK=sum(K);
if (card~=0)
c(l+1,1)=smKI/smK;
else
c(l+1,1)=999999999;
end
end
end
c=c(c(:,1)~=999999999,:);
c_global_min=c;
k_global=length(c(:,1));
k=k_global;
else
iter_v=iter_v+1;
%---------------------------------
% Begin updating labels
%---------------------------------
% Calculate region Pl of label l
if size(im, 3)==3 % Color image
for l=0:k-1
Pl=find(L==l);
card=length(Pl);
K1=kernel_RBF(im(Pl),c(l+1,1));K2=kernel_RBF(im(Pl),c(l+1,2));K3=kernel_RBF(im(Pl),c(l+1,3));
smKI(1)=sum(im(Pl).*K1); smKI(2)=sum(im(Pl+prod(sz(1:2))).*K2); smKI(3)=sum(im(Pl+2*prod(sz(1:2))).*K3);
smK1=sum(K1);smK2=sum(K2);smK3=sum(K3);
% Calculate contour Cl of region Pl
if (card~=0)
c(l+1,1)=smKI(1)/smK1;c(l+1,2)=smKI(2)/smK2;c(l+1,3)=smKI(3)/smK3;
else
c(l+1,1)=999999999;c(l+1,2)=999999999;c(l+1,3)=999999999;
area(l+1)=999999999;
end
end
end
if size(im, 3)== 1 % Gray-level image
for l=0:k-1
Pl=find(L==l);
card=length(Pl);
K=kernel_RBF(im(Pl),c(l+1,1));
smKI=sum(im(Pl).*K);
smK=sum(K);
% Calculate contour Cl of region Pl
if (card~=0)
c(l+1,1)=smKI/smK;
else
c(l+1,1)=999999999;
area(l+1)=999999999;
end
end
end
c=c(c(:,1)~=999999999,:);
k=length(c(:,1));
end
end
L=L_global_min;
energy_global_min;
c=c_global_min;
size(c,1)
iter;
%Show the results
if size(im, 3)==3 % Color image
img=zeros(sz(1),sz(2),3);
j=1;
imagesc(im); axis off; hold on;
for i=0:k_max-1
LL=(L_global_min==i);
is_zero=sum(sum(LL));
if is_zero
img(:,:,1)=img(:,:,1)+LL*c(j,1);
img(:,:,2)=img(:,:,2)+LL*c(j,2);
img(:,:,3)=img(:,:,3)+LL*c(j,3);
j=j+1;
end
if i~=i_ground
color=[rand rand rand];
contour(LL,[1 1],'LineWidth',2.5,'Color',color); hold on;
end
end
figure(2);
imagesc(img); axis off;
end
if size(im, 3)==1 % Gray-level image
img=zeros(sz(1),sz(2));
j=1;
imagesc(im); axis off; hold on; colormap gray;
for i=0:k_max-1
LL=(L_global_min==i);
is_zero=sum(sum(LL));
if is_zero
img(:,:,1)=img(:,:,1)+LL*c(j,1);
j=j+1;
end
if i~=i_ground
color=[rand rand rand];
contour(LL,[1 1],'LineWidth',2.5,'Color',color); hold on;
end
end
figure(2);
imagesc(img); axis off;
end
A possible solution is to set the variable initially to zeros(k_max, 1 ).

Segmenting cursive character (Arabic OCR)

I want to segment an Arabic word into single characters. Based on the histogram/profile, I assume that I can do the segmentation process by cut/segment the characters based on it's baseline (it have similar pixel values).
But, unfortunately, I still stuck to build the appropriate code, to make it works.
% Original Code by Soumyadeep Sinha
% Saving each single segmented character as one file
function [segm] = trysegment (a)
myFolder = 'D:\1. Thesis FINISH!!!\Data set\trial';
level = graythresh (a);
bw = im2bw (a, level);
b = imcomplement (bw);
i= padarray(b,[0 10]);
verticalProjection = sum(i, 1);
set(gcf, 'Name', 'Trying Segmentation for Cursive', 'NumberTitle', 'Off')
subplot(2, 2, 1);imshow(i);
subplot(2,2,3);
plot(verticalProjection, 'b-'); %histogram show by this code
% hist(reshape(input,[],3),1:max(input(:)));
grid on;
% % t = verticalProjection;
% % t(t==0) = inf;
% % mayukh = min(t)
% 0 where there is background, 1 where there are letters
letterLocations = verticalProjection > 0;
% Find Rising and falling edges
d = diff(letterLocations);
startingColumns = find(d>0);
endingColumns = find(d<0);
% Extract each region
y=1;
for k = 1 : length(startingColumns)
% Get sub image of just one character...
subImage = i(:, startingColumns(k):endingColumns(k));
% se = strel('rectangle',[2 4]);
% dil = imdilate(subImage, se);
th = bwmorph(subImage,'thin',Inf);
n = imresize (th, [64 NaN], 'bilinear');
figure, imshow (n);
[L,num] = bwlabeln(n);
for z= 1 : num
bw= ismember(L, z);
% Construct filename for this particular image.
baseFileName = sprintf('char %d.png', y);
y=y+1;
% Prepend the folder to make the full file name.
fullFileName = fullfile(myFolder, baseFileName);
% Do the write to disk.
imwrite(bw, fullFileName);
% subplot(2,2,4);
% pause(2);
% imshow(bw);
end
% y=y+1;
end;
segm = (n);
Word image is as follow:
Why the code isn't work?
do you have any recommendation of another codes?
or suggested algorithm to make it works, to do a good segmentation on cursive character?
Thanks before.
Replace this code part from the posted code
% 0 where there is background, 1 where there are letters
letterLocations = verticalProjection > 0;
% Find Rising and falling edges
d = diff(letterLocations);
startingColumns = find(d>0);
endingColumns = find(d<0);
with the new code part
threshold=max(verticalProjection)/3;
thresholdedProjection=verticalProjection > threshold;
count=0;
startingColumnsIndex=0;
for i=1:length(thresholdedProjection)
if thresholdedProjection(i)
if(count>0)
startingColumnsIndex=startingColumnsIndex+1;
startingColumns(startingColumnsIndex)= i-floor(count/2);
count=0;
end
else
count=count+1;
end
end
endingColumns=[startingColumns(2:end)-1 i-floor(count/2)];
No changes needed for the rest of the code.

connected component analysis in MATLAB

I want to apply connected component analysis on a grey scale image with considering pixels whose grey level is more than a threshold. then, I want to remove those connected components whose length is less than a threshold. please help me? I wrote following code in MATLAB, is it efficient?
thank you in advance.
%im = input image;
% alpha1 = 0.0001;
% alpha2 = 0.0001;
% [row col] = size(im);
%
%
% thr1 = mean(mean(im))-alpha1*std(std(im));
% BW = zeros(size(im));
%
% for rr = 1:row
% for cc = 1:col
% if im(rr,cc)>thr2
% BW(rr,cc) = 1;
% else
% BW(rr,cc) = 0;
% end
% end
% end
%
% CC = bwconncomp(BW);
% area_in_pixels = cellfun(#length,CC.PixelIdxList);
% thr2 = mean(area_in_pixels)-alpha2*std(area_in_pixels);
% idx = find(area_in_pixels <= thr3);
% for kk = 1:length(idx)
% aaa = idx(kk);
% BW(CC.PixelIdxList{aaa})=0;
% end
You can try regionprops instead to extract all objects in your image. With the code below you get the positions of all objects smaller than a threshold which you can manipulate or do what you need to do afterwards...
Comparably you can go through the different objects and extract the grey level and if it is below a threshold manipulate them.
% Threshold for the size in pixels that you want
threshold = 100;
% read your image
rawimage = imread('yourimage.jpg');
% create a 2D field by summing
im = sum(rawimage,3);
% label all objects that have 8 neighbours
IMAGE_labeled = bwlabel(im,8);
% get the properties of all elements
shapedata=regionprops (IMAGE_labeled,'all');
% get those elements that are smaller in size (area) than the threshold
index = find(cell2mat({shapedata(:).Area})<=threshold);
% make a contourplot of im
figure
contourf(im)
hold on
% creation of colormap with the size of all identified objects below the thres
mycolormap = jet(size(index,2));
% loop over all small objects, extraction of their position in the original file, plotting circles with different colors at the position of each small object
imap = 1;
mean_of_red = zeros(length(index),1);
for i = index
plot (shapedata(i).PixelList(:,1),shapedata(i).PixelList(:,2),'o','MarkerFaceColor',mycolormap(imap,:))
mean_of_red(i) = mean(mean(im(shapedata(i).PixelList(:,1),shapedata(i).PixelList(:,1),1)));
imap=imap+1;
end

How to save the segmented image automatically

I did a program on matlab for character segmentation of bengali script and i want to save the series of segmented image automatically in a specific folder. So anyone help me with the matlab code for saving image automatic
%%LINES SEGMENTATION:
close all;
clear all;
clc;
im=imread('page_1.tif');%read the image
%figure, imshow(im);
%%title('INPUT IMAGE WITH NOISE');
qw=im;
if size(im,3)==3 % RGB image %% Convert to gray scale
im=rgb2gray(im);
end
threshold = graythresh(im); %% Convert to binary image
im =~im2bw(im,threshold);
im = bwareaopen(im,10); %% Remove all object containing fewer than 60 pixels
%figure(2) %% Show image binary image
%imshow(~im);
%title('INPUT IMAGE WITHOUT NOISE');
%figure, area(im);
%find Area of Interest:
a=(~im);
ijk=~a;
xy=sum(ijk,2);
measurements = regionprops(xy == 0, 'Area', 'PixelIdxList');
%Get indexes of those regions that are >= 20 in length.
fiveLongRegions = find([measurements.Area] >= 3);
theIndexes = vertcat(measurements(fiveLongRegions).PixelIdxList);
c=a;
c(theIndexes,:)=0;
%figure, imshow(c);
%title('AREA OF INTEREST FOR LINE SEGMENT');
ca=~c;
%Segmentation of line:
[x,y]=size(ca);
mat1=sum(ca,2);%sum the elements of bwrowise and save into column matrix mat1
mat2=y-mat1;%subtract each element of the sum matrix(mat1) from the width length(no. of columns)
mat3=mat2~=0;
mat4=diff(mat3);
index1=find(mat4);
[q,w]=size(index1);%size of index2 matrix is q*w
kap=1;
lam=1;
%iii=1;
%ii=1;
while kap<((q/2)+1);%number of loops=number of lines
k=1;
mat5=([]);
for j=(index1(lam)+1):1:index1(lam+1)
mat5(k,:)=c(j,:); %store the line segmented matrix
k=k+1;
end
lam=lam+2;
kap=kap+1;
figure, imshow(mat5);
%%imsave();
%%WORDS SEGMENTATION:
bwword=im2bw(mat5);%convert the image im into binary(black and white)
aword=~bwword;
bword=sum(aword,1);
%%figure, area(b);
%%Measure lengths of all "0" regions.
measurementsword = regionprops(bword == 0, 'Area', 'PixelIdxList');
% Get indexes of those regions that are >= 20 in length.
fiveLongRegionsword = find([measurementsword.Area] >= 5);
theIndexesword = vertcat(measurementsword(fiveLongRegionsword).PixelIdxList);
cword=aword;
cword(:,theIndexesword)=1;
%%figure, imshow(c);
dword=~cword;
%%figure, imshow(dword);
%%title('AREA OF INTERESRT FOR WORD SEGMENTATION IMAGE');
[xword,yword]=size(cword);
mat1word=sum(cword,1);%sum the elements of bwrowise and save into column matrix mat1
mat2word=xword-mat1word;%subtract each element of the sum matrix(mat1) from the width length(no. of columns)
mat3word=mat2word~=0;
mat4word=diff(mat3word);
index1word=find(mat4word);
[qword,wword]=size(index1word);%size of index2 matrix is q*w
kapword=1;
lamword=1;
%%iii=1;
%%ii=1;
while kapword<((wword/2)+1);%number of loops=number of lines
kword=1;
mat5word=([]);
for jword=(index1word(lamword)+1):1:index1word(lamword+1)
mat5word(:,kword)=bwword(:,jword); %store the word segmented matrix
kword=kword+1;
end
lamword=lamword+1;
kapword=kapword+1;
figure, imshow(mat5word);
%imsave();
%%CHARACTER SEGMENTATION:
bwcha=im2bw(mat5word);%convert the image im into binary(black and white)
acha=~bwcha;
mat1cha=sum(a,2);
%figure, area(mat1);
xcha=find(mat1cha>70);
ycha=acha;
ycha(xcha,:)=0;
ycha = bwareaopen(ycha,20);
figure,imshow(ycha);
%figure, area(y);
%mat2=sum(y,2);
%x1=find(mat2<7);
%y1=y;
%y1(x1,:)=0;
%y1 = bwareaopen(y1,15);
%z=~y1;
%figure, imshow(z);
[Lcha, bcha,]=bwlabel(ycha); %% Label connected components
propiedcha=regionprops(Lcha,'BoundingBox'); %% Measure properties of image regions
for ncha=1:size(propiedcha,1) %% Plot Bounding Box
rectangle('Position',propiedcha(ncha).BoundingBox,'EdgeColor','g','LineWidth',1);
end
for ncha=1:bcha %% Objects extraction
[rcha,ccha] = find(Lcha==ncha);
n1cha=ycha(min(rcha):max(rcha),min(ccha):max(ccha));
figure, imshow(~n1cha);
%pause(0.2)
%imsave();
end
end
end
`enter co%%LINES SEGMENTATION:
close all;
clear all;
clc;
im=imread('page_1.tif');%read the image
%figure, imshow(im);
%%title('INPUT IMAGE WITH NOISE');
qw=im;
if size(im,3)==3 % RGB image %% Convert to gray scale
im=rgb2gray(im);`enter code here`
end
threshold = graythresh(im); %% Convert to binary image
im =~im2bw(im,threshold);
im = bwareaopen(im,10); %% Remove all object containing fewer than 60 pixels
%figure(2) %% Show image binary image
%imshow(~im);
%title('INPUT IMAGE WITHOUT NOISE');
%figure, area(im);
%find Area of Interest:
a=(~im);
ijk=~a;
xy=sum(ijk,2);
measurements = regionprops(xy == 0, 'Area', 'PixelIdxList');
%Get indexes of those regions that are >= 20 in length.
fiveLongRegions = find([measurements.Area] >= 3);
theIndexes = vertcat(measurements(fiveLongRegions).PixelIdxList);
c=a;
c(theIndexes,:)=0;
%figure, imshow(c);
%title('AREA OF INTEREST FOR LINE SEGMENT');
ca=~c;
%Segmentation of line:
[x,y]=size(ca);
mat1=sum(ca,2);%sum the elements of bwrowise and save into column matrix mat1
mat2=y-mat1;%subtract each element of the sum matrix(mat1) from the width length(no. of columns)
mat3=mat2~=0;
mat4=diff(mat3);
index1=find(mat4);
[q,w]=size(index1);%size of index2 matrix is q*w
kap=1;
lam=1;
%iii=1;
%ii=1;
while kap<((q/2)+1);%number of loops=number of lines
k=1;
mat5=([]);
for j=(index1(lam)+1):1:index1(lam+1)
mat5(k,:)=c(j,:); %store the line segmented matrix
k=k+1;
end
lam=lam+2;
kap=kap+1;
figure, imshow(mat5);
%%imsave();
%%WORDS SEGMENTATION:
bwword=im2bw(mat5);%convert the image im into binary(black and white)
aword=~bwword;
bword=sum(aword,1);
%%figure, area(b);
%%Measure lengths of all "0" regions.
measurementsword = regionprops(bword == 0, 'Area', 'PixelIdxList');
% Get indexes of those regions that are >= 20 in length.
fiveLongRegionsword = find([measurementsword.Area] >= 5);
theIndexesword = vertcat(measurementsword(fiveLongRegionsword).PixelIdxList);
cword=aword;
cword(:,theIndexesword)=1;
%%figure, imshow(c);
dword=~cword;
%%figure, imshow(dword);
%%title('AREA OF INTERESRT FOR WORD SEGMENTATION IMAGE');
[xword,yword]=size(cword);
mat1word=sum(cword,1);%sum the elements of bwrowise and save into column matrix mat1
mat2word=xword-mat1word;%subtract each element of the sum matrix(mat1) from the width length(no. of columns)
mat3word=mat2word~=0;
mat4word=diff(mat3word);
index1word=find(mat4word);
[qword,wword]=size(index1word);%size of index2 matrix is q*w
kapword=1;
lamword=1;
%%iii=1;
%%ii=1;
while kapword<((wword/2)+1);%number of loops=number of lines
kword=1;
mat5word=([]);
for jword=(index1word(lamword)+1):1:index1word(lamword+1)
mat5word(:,kword)=bwword(:,jword); %store the word segmented matrix
kword=kword+1;
end
lamword=lamword+1;
kapword=kapword+1;
figure, imshow(mat5word);
%imsave();
%%CHARACTER SEGMENTATION:
bwcha=im2bw(mat5word);%convert the image im into binary(black and white)
acha=~bwcha;
mat1cha=sum(a,2);
%figure, area(mat1);
xcha=find(mat1cha>70);
ycha=acha;
ycha(xcha,:)=0;
ycha = bwareaopen(ycha,20);
figure,imshow(ycha);
%figure, area(y);
%mat2=sum(y,2);
%x1=find(mat2<7);
%y1=y;
%y1(x1,:)=0;
%y1 = bwareaopen(y1,15);
%z=~y1;
%figure, imshow(z);
[Lcha, bcha,]=bwlabel(ycha); %% Label connected components
propiedcha=regionprops(Lcha,'BoundingBox'); %% Measure properties of image regions
for ncha=1:size(propiedcha,1) %% Plot Bounding Box
rectangle('Position',propiedcha(ncha).BoundingBox,'EdgeColor','g','LineWidth',1);
end
for ncha=1:bcha %% Objects extraction
[rcha,ccha] = find(Lcha==ncha);
n1cha=ycha(min(rcha):max(rcha),min(ccha):max(ccha));
figure, imshow(~n1cha);
%pause(0.2)
%imsave();
end
end
end
de here`ally i am providing my code
Assuming you are trying to write to folder all n1cha images that you show at the end of your code.
You'll need to maintain a counter that counts how many characters you already saved and then use imwrite to save the characters:
% init variables before loop
imgFolder = 'path/to/saved/images';
counter = 1;
while kap<((q/2)+1);%number of loops=number of lines
% your code here... nested loops...
% ...
% finally you get to this loop:
for ncha=1:bcha
% extract the character...
imwrite( n1cha, fullfile( imgFolder, sprintf( 'char_%04d.png', counter ) ) );
counter = counter + 1;
end
end
If you want to save it to folder with name 'Folder', here it goes(I'm using and copy paste your code):
folder = "Folder"; // **the path and name of your folder**<br/>
for ncha=1:bcha %% Objects extraction<br/>
[rcha,ccha] = find(Lcha==ncha);<br/>
n1cha=ycha(min(rcha):max(rcha),min(ccha):max(ccha));<br/>
figure, imshow(~n1cha);<br/>
imwrite(n1cha, folder); **//code to save it to folder 'Folder' automatically**<br/>
end

index out of bounds in matlab [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I am not able to get how to run it, can anyone help me on this please.
I am receiving this error :
K>> [minutiae_valid]=postprocess_TICO(B,im,~K)
??? Attempted to access wind(273,386); index out of bounds because size(wind)=[368,385].
Error in ==> postprocess_TICO at 214
if (thinned(p,q)==1)&&(wind(p,q)==0)
postprocess_Tico
function [minutiae_valid]=postprocess_TICO(minutiae_valid,im1,thinned)
% clc;
% close all;
% clear all;
cell=16;%total no. of cells needed in quantization;
% im1= imread('E:\FINGERPRINT DATABASE\FVC2002\Dbs\Db1_a\16_6.tif');
wl=(33-1)/2;
% no=20;
% no2=20;
% nox = 0;
% noy = 0; %to choose border area
%
m=size(im1,1);
n=size(im1,2);
%m=(round(m/cell))*cell;
%n=(round(n/cell))*cell;
% im1=imresize(im1,[m n]);
% im=double(im1);
% figure;
% subplot(1,2,1);
% imshow(uint8(im));
% title('original input image');
%
% %Identify ridge-like regions and normalise image--------------------------
% blksze = 10;
% thresh =30;
% M0=100;
% STD0=150;
% [thinim, mask] = imgenhance(im, blksze, M0, STD0);
% subplot(1,2,2); subimage((thinim));
% title('Improved thinned input image', 'FontSize', 12);
% INPUT_IMG=thinim;
%
% %minutiae extraction
% thinned= INPUT_IMG;
% img = INPUT_IMG;
% [minutiae, minutiae_img, combined] = findminutiae(thinned, img);
% totminu_I = size(minutiae,1)
% figure,
% subplot(1,2,1), subimage(combined), title('minutiae before postprocess.')
% %______________________________________________________________
% %TO FIND BOUNDARY OF INPUT IMAGE AS WELL AS REGION OF FALSE MINU
% mask_input=mask;
% border=uint8(zeros(m,n));
%
% [m,n]=size(mask);
% validr=uint8(zeros(m,n));
% thin_temp=thinned;
% for i=1:m
% for j=2:n-1
% if((mask_input(i,j-1)==0)&&(mask_input(i,j)==1)&&(j<=n-no))
% border(i,j)=1;
% validr(i,j-nox:j+no)=1;
% thin_temp(i,j-nox:j+no)=1;
% end
%
% if ((mask_input(i,j+1)==0)&&(mask_input(i,j)==1)&&(j>no))
% border(i,j)=1;
% validr(i,j+nox:-1:j-no)=1;
% thin_temp(i,j+nox:-1:j-no)=1;
% end
%
% end
% end
%
% for i=1:m
% for j=1:n-1:n
% if (mask_input(i,j)==1)
% if (j==1)
% border(i,j)=1;
% validr(i,j:j+no)=1;
% thin_temp(i,j:j+no)=1;
% end
% if (j==n)
% border(i,j)=1;
% validr(i,j:-1:j-no)=1;
% thin_temp(i,j:-1:j-no)=1;
% end
% end
% end
% end
%
%
%
% for j=1:n
% for i=2:m-1
% if((mask_input(i-1,j)==0)&&(mask_input(i,j)==1)&&(i<=m-no))
% border(i,j)=1;
% validr(i-noy:i+no,j)=1;
% thin_temp(i-noy:i+no,j)=1;
% end
% if((mask_input(i+1,j)==0)&&(mask_input(i,j)==1)&&(i>no))
% border(i,j)=1;
% validr(i+noy:-1:i-no,j)=1;
% thin_temp(i+noy:-1:i-no,j)=1;
% end
%
% end
% end
%
% for j=1:n
% for i=1:m-1:m
% if (mask_input(i,j)==1)
% if (i==1)
% border(i,j)=1;
% validr(i:i+no,j)=1;
% thin_temp(i:i+no,j)=1;
% else validr(i:-1:i-no,j)=1;
% thin_temp(i:-1:i-no,j)=1;
% end
% end
% end
% end
%
% %___________________________________________________________________
% % removing minu at the border of roi
% for x=1:size(thinned,1)
% for y=1:size(thinned,2)
% if ((validr(x,y)==1)&&(thinned(x,y)==1))
% combined(x,y,:)=[255,255,255];
% minutiae_img(x,y,:)=[0,0,0];
%
% end
% end
% end
%
% for i=1:totminu_I
% x=minutiae(i,1);
% y=minutiae(i,2);
% if ((validr(x,y)==1)&&(thinned(x,y)==1))
% minutiae(i,:)=0;
% end
% end
% %__________________________
%
% subplot(1,2,2), subimage(combined), title('after boundary effect ')
% minu_count=1;
% minutiae_valid(minu_count, :) = [0,0,0,0]; %to make x, y, CN, theta value of minutiae not in border region.
% for i=1:totminu_I
% CN=minutiae(i,3);
% if (CN~=0)
% minutiae_valid(minu_count, :) = minutiae(i,:);
% minu_count = minu_count + 1;
% end
% end
% totminu_I= minu_count-1;
k=size(minutiae_valid);
totminu_I=k(1,1);
%FALSE RIDGE BIFURCATION
for i=1:totminu_I
if minutiae_valid(i,3)==3
wind=ones(m,n);
xi= minutiae_valid(i,1);
yi=minutiae_valid(i,2);
x=xi;
y=yi;
wind(xi-wl:xi+wl,yi-wl:yi+wl)=0; %window of size 25 cross 25
wind(xi,yi)=-1;
%mark '1', '2', '3'.
value=0;
r=x-1;
for c=y-1:y+1
if (thinned(r,c)==1)&&(wind(r,c)==0)
value=value+1;
wind(r,c)=value;
end
end
c=y+1;
for r=x-1:x+1
if (thinned(r,c)==1)&&(wind(r,c)==0)
value=value+1;
wind(r,c)=value;
end
end
r=x+1;
for c=y+1:-1:y-1
if (thinned(r,c)==1)&&(wind(r,c)==0)
value=value+1;
wind(r,c)=value;
end
end
c=y-1;
for r=x+1:-1:x-1
if (thinned(r,c)==1)&&(wind(r,c)==0)
value=value+1;
wind(r,c)=value;
end
end
for value=1:3 %search '1'/'2/'3' value pixel arond the minutia point in the window.
for p=x-1:x+1
for q=y-1:y+1
if wind(p,q)==value
xi=p;
yi=q;
end
end
end
cnt=0;
while(xi>x-wl)&&(xi<x+wl)&&(yi>y-wl)&&(yi<y+wl) %mark '1'/'2'/'3' to the adjacent connected pixels
k=0;
for p=xi-1:xi+1
for q=yi-1:yi+1
if (thinned(p,q)==1)&&(wind(p,q)==0)
wind(p,q)=value;
k=k+1;
if k==1
x1=p;
y1=q;
end
if k==2 %more than one connected pixel
cnt=cnt+1;
x2=p;
y2=q;
t1=x1;
x1=x2;
x2=t1;
t2=y1;
y1=y2;
y2=t2;
%___________
xi=x2;
yi=y2;
while(xi>x-wl)&&(xi<x+wl)&&(yi>y-wl)&&(yi<y+wl)
k=0;
flag_see=0;
for p=xi-1:xi+1
for q=yi-1:yi+1
if (thinned(p,q)==1)&&(wind(p,q)==0)
wind(p,q)=value;
flag_see=1;
x3=p;
y3=q;
k=k+1;
end
end
end
if(flag_see==1)
xi=x3;
yi=y3;
else
xi=p;
yi=q;
end
if k==0
break
end
end
% xi=x1;
% yi=y1;
end
end
end
end
xi=x1;
yi=y1;
if k==0
break
end
end
end
% figure,subimage(wind);
%to count 0-1, 0-2, 0-3 transition around the boundary clkwise
T=1;
for v=1:3
T0v=0;
r=x-wl;
for c=y-wl:y+(wl-1)
if (wind(r,c)==0)&&(wind(r,c+1)==v)
T0v=T0v+1;
end
end
c=y+wl;
for r=x-wl:x+(wl-1)
if (wind(r,c)==0)&&(wind(r+1,c)==v)
T0v=T0v+1;
end
end
r=x+wl;
for c=y+wl:-1:y-(wl-1)
if (wind(r,c)==0)&&(wind(r,c-1)==v)
T0v=T0v+1;
end
end
c=y-wl;
for r=x+wl:-1:x-(wl-1)
if (wind(r,c)==0)&&(wind(r-1,c)==v)
T0v=T0v+1;
end
end
T1=T0v==1;
T=T & T1;
end
if T~=1
minutiae_valid(i,:)=[0 0 0 0];
combined(x,y,:)=[255,255,255];
end
end
end
minu_count=1;
minutiae_valid_final(minu_count, :) = [0,0,0,0]; %to make x, y, CN, theta value of minutiae not in border region.
for i=1:totminu_I
CN = minutiae_valid(i,3);
if (CN~=0)
minutiae_valid_final(minu_count, :) = minutiae_valid(i,:);
minu_count = minu_count + 1;
end
end
% totminu_I= minu_count-1;
minutiae_valid = minutiae_valid_final;
% figure, subimage(combined);
At lines 212 and 213 you create nested loops that loop over nine elements of wind looking for elements that match some sort of condition. When you find one, you change the center of your nine element block.
The problem arises when the center of your block is on an edge of wind. When you look over the nine elements centered at an edge you must not access indices in the same way, otherwise you get the error as in above. To illustrate a simple case of this:
a = rand(4,4);
for p=2:4
for q = 1:3
tmp += a(p,q)
end
end
sums the 9 elements of a (a square array) centered at (3,2).
a = rand(4,4);
for p=3:5
for q = 1:3
tmp += a(p,q)
end
end
will generate the same error that you have when it tries to access a(5,1) because this element of the array does not exist. The correct way to fix this depends on what you're trying to do, but that's most definitely beyond the scope of your question, and our ability to figure out.
I hope this helps.
Echoing some of the comments, I'd like to offer you a piece of advice. In the future, you're much more likely to get on taget, quality answers if you can boil your question down to the shortest possible test case. This is also a valuable step in debugging your own code. Figuring out how to construct a test case will often make the answer to your problem apparent. When it's not apparent, Stackoverflow is an excellent resource.