%预处理
I=imread('D:\Matlab\work\sample1.jpg'); %读入JPG彩色图像文件
%灰度化、二值化
J=rgb2gray(I); %灰度化后的数据存入数组
figure,imshow(J) %显示灰度化后的图像,也是均衡化前的样品
title('灰度化后的图像')
level=graythresh(J); %求阈值 Ostu法
BW=im2bw(J,level);
figure,imshow(BW)
title('二值化后的图像')
%行字切分
[width, length] = size(BW); % 求图片长宽
marRow = ones(width, 1); % 存储行的像素值的 width*1 矩阵
%%%%%%%%%%%%%%%%%% 求行的投影值 %%%%%%%%%%%%%%%%%%
for row = 1 : width
rFlag = 0; % 记录行的像素点
for col = 1 : length
if BW(row, col) == 0
rFlag = rFlag + 1; %记录像素点
end
end
marRow(row, 1) = rFlag; %记录投影点R+1;
end
figure,plot(marRow)
title('行投影积分')
bottomR = [];
topR = [];
n1 = 1;
for row = 1 : width-1
if ((marRow(row, 1) == 0) && (marRow(row+1, 1) ~= 0))
topR(n1) = row;
end
if ((marRow(row, 1) ~= 0) && (marRow(row+1, 1) == 0))
bottomR(n1) = row+1; n1 = n1 + 1;
end
end
%%%%%%%%%%%%%%%%%% 求列的投影值 %%%%%%%%%%%%%%%%%%
marCol = ones(1,n1-1 , length); % 存储每行列的像素值的 1*行*length 矩阵
% numC = 1;
for h = 1 : n1-1
topRh = topR(h);
bottomRh = bottomR(h);
for col = 1 : length
cFlag = 0; % 记录列的像素点
for row = topRh : bottomRh
if BW(row,col) == 0
cFlag = cFlag + 1; %记录像素点
end
end
marCol(1,h, col) = cFlag; %记录投影点
end
end
leftC = [ ; ];
rightC = [ ; ];
n2 = ones(1,n1);
for R = 1 : n1-1;
for col = 1 : length-1
if ((marCol(1,R, col) == 0) && (marCol(1,R, col+1) ~= 0) )
leftC(R,n2(1,R)) = col;
end
if ((marCol(1,R, col) ~= 0) && (marCol(1,R, col+1) == 0) )
rightC(R,n2(1,R)) = col+1;n2(1,R) = n2(1,R) + 1;
end
end
end
row = 1;
col = 1;
% bottom = 1;
xflag = 1;
% right = 1;
file = [];
r = 1; c= 1;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 分 割 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for r = 1 : n1-1
bottom = bottomR(r);
top = topR(r);
for c = 1 : n2(1,r)-1
left = leftC(r,c);
right = rightC(r,c);
for rpix = 1 : bottom - top
for cpix = 1 : right - left
file(rpix, cpix) = BW(top + rpix -1, left + cpix -1);
end
end
newName = sprintf('new%ld.jpg', xflag);
imwrite(file, newName);
xflag = xflag + 1;
end
end