这是为了使用halcon中一些比较好的算子,在matlab中比较难找到。但是在halcon中得到了轮廓后,又想使用matlab进行进一步处理。所以写了两个转换函数:XLD2Cell,Cell2XLD
首先说明halcon写入,然后是XLD2Cell函数,Cell2XLD函数,最后是halcon读入。
今天查到歪国人可以在matlab中调用halcon函数,还没有仔细研究。目前这个转换函数还是很有用的。
一、Halcon XLD 读写XLD文件:
写:write_contour_xld_arc_info读:read_contour_xld_arc_info
例如:
…
edges_sub_pix (Image, edges, 'deriche1', 2, 20, 40) * 剔除过长或者过短的边缘
dev_set_color ('green')
select_contours_xld (edges, SelectedContours, 'contour_length', 10, 2000, -0, 10)
write_contour_xld_arc_info (SelectedContours, 'result.txt’)
注意:halcon帮助里的例子是存成后缀名为‘gen’的文件,实际上用txt后缀名并不影响存储和读取。 写入后的数据文件如下:
1
356.12850952 221.37731934
356.56933594 220.53341675
…
358.42843628 202.51916504
END
2
87.46049500 204.51058960
87.29135132 203.54479980
END
…
579
527.59777832 377.09463501
526.52301025 376.65286255
…
517.60430908 376.55984497
END
END
注意:数据文件的格式是:首先是计数,然后是轮廓点的坐标,这条轮廓记录完就有END,直到最后一条轮廓END之后,额外加一个END表示数据文件的结束。
二、XLD2Cell函数: 从txt文件读入数据,在matlab里梳理成cell的形式
function c = XLD2Cell(filename)
% 从halcon中用XLD格式轮廓生成写出的文件读取数据,转换成matlab中cell格式
%
% !!注意:halcon中xld需要存成txt格式文件,且只存轮廓,不存其他非轮廓或者非xld变量。
%
% 输入:filename:字符串,如‘result.txt'.
% 应代表文本文件,后缀名为txt,但halcon生成的是后缀名为gen文件,经测试也可以
% 输出:c:为cell数据,cell里每个[]里为N*2的轮廓点坐标
fidin=fopen(filename);
c = {};
i = 0; % 计数器,记录有多少条轮廓
while ~feof(fidin) % 判断是否到了文件结尾
tline=fgetl(fidin); % 逐行读入 % 注意读入的是string形式的
% disp(tline)
abuf = str2num(tline);
if abuf == round(abuf) %表明是一个轮廓的开始
newBegin = []; % 创建一个矩阵然后重新开始循环
i = i+1;
continue;
end
if tline(1) == 'E' % 如果遇到每个轮廓的结尾处
c{i}= newBegin;
continue;
end
if abuf(1) > floor(abuf(1))
newBegin = [newBegin;abuf];
continue;
end
end
三、Cell2XLD:在matlab里将cell的形式的轮廓,写入能够被halcon读入的格式(如一中所示)
function Cell2XLD(c,filename)
% matlab中cell转换成halcon的XLD格式的轮廓数据文件,可以被
% halcon的read_contour_xld_arc_info函数直接读取
%
% 输入:c:为cell数据,cell里每个[]里为N*2的轮廓点坐标
% filename:输出数据存放文件的文件名
% % 输出:b:二值变量,指示是否成功输出,成功则b=1,失败则b=0;
% c = ce;
% % filename= 'result30.txt';
nc = length(c); % 轮廓数量
fid=fopen(filename,'a');
e = 'END';
for i = 1:nc
fprintf(fid,'%d \r\n',i); % 轮廓的编号
fprintf(fid,'%f %f \r\n',c{i}'); % 轮廓点坐标
fprintf(fid,'%s \r\n',e); % 每个轮廓结束的END
if i == nc
fprintf(fid,'%s \r\n',e); % 所有结束了的END
end
end
四、函数使用示例
XLD txt --> cell
filename= 'result.txt';
c = XLD2Cell(filename);
Cell --> XLD txt
filename= 'result32.txt';
Cell2XLD(ce,filename);