Halcon红黄蓝颜色识别之训练学习方法(第一种方法)
read_image (Image, 'C:/Users/Administrator/Desktop/halcon识别图片/红黄蓝.jpg')
dev_close_window ()
dev_open_window (0, 0, 557, 416, 'black', WindowHandle)
dev_display (Image)
Regions:=['红','黄','蓝','白']
dev_set_draw ('margin')
dev_set_line_width (3)
gen_empty_obj (Classes)
for i := 1 to |Regions| by 1
dev_display (Image)
dev_display (Classes)
disp_message (WindowHandle, '请选定区域:', 'window', 12, 12, 'black', 'true')
*底下这几个if语句主要将自己画出的几个区域组成区域数组Classes
if(i==1)
gen_circle (ROI_1, 1003.35, 544.132, 202.341)
concat_obj (Classes, ROI_1, Classes)
continue
else
endif
if(i==2)
gen_circle (ROI_2, 992.962, 1340.4, 190.235)
concat_obj (Classes, ROI_2, Classes)
continue
else
endif
if(i==3)
gen_circle (ROI_3, 342.192, 1009.48, 207.301)
concat_obj (Classes, ROI_3, Classes)
continue
else
endif
if(i==4)
gen_circle (ROI_0, 418.346, 1578.24, 317.809)
gen_circle (TMP_Region, 369.885, 389.015, 372.589)
union2 (ROI_0, TMP_Region, ROI_0)
gen_circle (TMP_Region, 1217.96, 954.329, 180.836)
union2 (ROI_0, TMP_Region, ROI_0)
concat_obj (Classes, ROI_0, Classes)
continue
else
endif
endfor
create_class_mlp (3, 10, 4, 'softmax', 'normalization', 10, 42, MLPHandle)
add_samples_image_class_mlp (Image, Classes, MLPHandle)
disp_message (WindowHandle, '开始训练模型', 'window',12, 12, 'black', 'true')
train_class_mlp (MLPHandle, 200, 1, 0.01, Error, ErrorLog)
*测试
for j:=1 to 4 by 1
read_image (test, 'C:/Users/Administrator/Desktop/halcon识别图片/识别红黄蓝/'+j)
dev_display (test)
*输入测试图像,用上述训练形成的模型句柄将此图像进行多层分类,ClassRegions是该图像分类成的几个种类形成的数组
classify_image_class_mlp (test, ClassRegions, MLPHandle, 0.5)
*对该图像分类后的几个种类一个个遍历,并对其进行处理,找到自己想要的区域进行分割提取并显示
for k := 1 to 4 by 1
select_obj (ClassRegions, ObjectSelected, k)
dev_display ( ObjectSelected)
opening_circle (ObjectSelected, RegionOpening, 30)
connection (RegionOpening, ConnectedRegions)
select_shape (ConnectedRegions, SelectedRegions, ['area','circularity'], 'and', [149786,0.41087], [497772,0.99007])
area_center (SelectedRegions, Area1, Row4, Column4)
if(Area1<150000 or Area1>400000 and Area1<430000)
continue
endif
*下面这几句主要用于将形状选择出来的不规则圆进行拟合成标准圆
* shape_trans (SelectedRegions, RegionTrans, 'convex')
* gen_contour_region_xld (RegionTrans, Contours, 'border')
* fit_circle_contour_xld (Contours, 'algebraic', -1, 0, 0, 3, 2, Row, Column, Radius, StartPhi, EndPhi, PointOrder)
* gen_circle (Circle, Row, Column, Radius)
*显示
dev_display (test)
dev_display (SelectedRegions)
disp_message (WindowHandle,Regions[k-1], 'window', 0, 0, 'black', 'true')
disp_message (WindowHandle, '该圆面积是'+Area1,'window', 25, 0, 'black', 'true')
disp_message (WindowHandle, '该圆中心横纵坐标是'+(Row4+','+Column4),'window', 50, 0, 'black', 'true')
stop ()
endfor
endfor