2013年国赛B题前两问原创代码
学习笔记仅供学习参考(MATLAB图像处理)
main.m
tic
clear;clc;
%% 得到边缘矩阵和n值
get_image_edgeblack = zeros(19,2);%初始化边缘矩阵
get_n = zeros(19,1);
%找到文件的名字
for i = 0:1:18
if i <= 9
f_n = ['00',num2str(i),'.bmp'];
else
f_n = ['0',num2str(i),'.bmp'];
end
[Imedge,n] = getimageedge_n(f_n);%获得该碎片的边缘矩阵和n值
get_image_edgeblack(i+1,1) = Imedge(1);%将其左边缘数据存储在get_image_edgeblack矩阵第一列中
get_image_edgeblack(i+1,2) = Imedge(2);%将其右边缘数据存储在get_image_edgeblack矩阵第二列中
get_n(i+1) = n;%将n的值存储在get_n矩阵中,后续要求最大值
end
%%
chip_pool = 1:19;%初始化碎片池为各自标号
shred = find(get_image_edgeblack(:,1)==0);%找到最开始的一个碎片,其特征为左边缘全白(0的个数为0)
best_list = zeros(19,1);%初始化最好序列为全0矩阵
best_list(1) = shred;%对最好序列赋初值为shred
chip_pool(shred) = 0;%将shred项目从碎片池中剔除
n = 28;%将把一个碎片分为28行
% global m p
% p = min(get_n);%要移除每张图片上p个像素点
% m = (1980-min(get_n))/n;%行间占有多少个像素点
% m = floor(m);
processing_object = shred;%正在处理的项目为shred
for i = 2:19
this_step_best = find_best_in_chip_pool(chip_pool,processing_object,n);%用此函数返回找到的下一个最优解
best_list(i) = this_step_best;%更新最好序列为找到的最优解
processing_object = this_step_best;%更改正在处理的项目为找到的最优解
chip_pool(this_step_best) = 0;%将找到的最优解剔除碎片池
end
%% 将碎片拼接成图像
im = [];
for i = 1:19
order = best_list(i)-1;
if order <= 9
f_n = ['00',num2str(order),'.bmp'];
else
f_n = ['0',num2str(order),'.bmp'];
end
Im = imread(f_n);
im = [im,Im];
end
imshow(im)
toc
getonelineedge.m
function [left_value,right_value] = getonelineedge(f_n,line,n)
Im = imread(f_n);
Im = imbinarize(Im);
Im = Im+0;
left_value = 0;
right_value = 0;
% left_value = sum(Im(38+69*line-line:38+69*line,1) == 0);
% right_value = sum(Im(38+69*line-line:38+69*line,72) == 0);
for i = line*69-69+1:line*69
if Im(i,1) == 0
left_value = left_value + 1;
end
if Im(i,72) == 0
right_value = right_value +1;
end
end
getimageedge_n.m
function [Imedge,n] = getimageedge_n(f_n)
Im = imread(f_n);
%将图像二值化
Im = imbinarize(Im);
Im = Im + 0;
%获取图像左右两侧黑色像素点的个数
Imedge(1) = sum(Im(:,1)==0);
Imedge(2) = sum(Im(:,72)==0);
n = -1;
for i = 1:1980
for j = 1:72
if Im(i,j) == 0
if n<0
n = i;
end
end
end
this_step_best = find_best_in_chip_pool.m
function this_step_best = find_best_in_chip_pool(chip_pool,processing_object,n)
[~,col] = find(chip_pool~=0);%将碎片池中不为零的元素所对应的标号放在col中
len = length(col);% col的长度就是碎片池中除了被剔除元素的个数
M = zeros(len,1);%M为两碎片间匹配度
for i = 1:len
m = 0;%m为两行间的匹配度
for k = 1:n
line = k;%正在比较第k行
compared_with = col(i); %正在和chip_pool中第i个不为0的元素比较
if processing_object-1 > 9
f_n = ['0',num2str(processing_object-1),'.bmp'];
else
f_n = ['00',num2str(processing_object-1),'.bmp'];
end
[~,b] = getonelineedge(f_n,line,n);%调用getonelineedge函数获得正在处理元素第j行的右边黑色像素点的个数
if compared_with-1 > 9
f_n = ['0',num2str(compared_with-1),'.bmp'];
else
f_n = ['00',num2str(compared_with-1),'.bmp'];
end
[c,~] = getonelineedge(f_n,line,n);%调用getonelineedge函数获得要比较碎片的第j行左边黑色像素点个数
if max(b,c)~=0
m = m+ min(b,c)/max(b,c);%计算并累加该行两碎片的匹配度
end
end
M(i) = m;%将该碎片与正在处理碎片的匹配度存储到M矩阵中
end
[row,~] = find(M == max(M));%找到与正在处理碎片匹配度最好的一个碎片
this_step_best = col(row);%返回此过程找到的最佳碎片,其位置为col(row)