Halcon红黄蓝颜色识别之转RGB后阈值分割实现(仅能识别单个识别)(第二种方法)
for k := 1 to 3 by 1
read_image (Image, 'C:/Users/Administrator/Desktop/halcon识别图片/识别红黄蓝/'+k+'.jpg')
dev_close_window ()
dev_open_window (0, 0, 557, 416, 'black', WindowHandle)
dev_display (Image)
dev_set_draw ('margin')
dev_set_line_width (3)
*RGB图像分别对应Image_R, Image_G, Image_B
decompose3 (Image, Image_R, Image_G, Image_B)
gen_empty_obj (ImageConcat)
*将转化成的RGB三个通道图像全部放入ImageConcat这个空区域中
concat_obj (Image_R, Image_G, ObjectsConcat)
concat_obj (ObjectsConcat, Image_B, ImageConcat)
*下面三组最大最小阈值用于红黄蓝三种颜色的对应好提取的RGB图像中的一个
min_threshold := [45, 6, 18]
max_threshold := [65, 31, 47]
*此处最小最大区域完全可以用一组,此处留有数组为了留一定修改空间
min_area := [100000, 100000, 100000]
max_area := [500000, 5000000, 5000000]
try
for i := 1 to 3 by 1
select_obj (ImageConcat, ImageSelected, i)
for j := 1 to 3 by 1
threshold (ImageSelected, Regions, min_threshold[j - 1], max_threshold[j - 1])
opening_circle (Regions, RegionOpening, 8)
*多个区域
connection (RegionOpening, ConnectedRegions)
*面积选择
select_shape (ConnectedRegions, SelectedRegions, ['area','circularity'], 'and', [min_area[j - 1],0.4937], [max_area[j - 1],1])
fill_up (SelectedRegions, RegionFillUp)
shape_trans (RegionFillUp, RegionTrans, 'convex')
area_center (RegionTrans, Area, Row, Column)
if (Area<150000 or Area>450000)
continue
else
a := min_threshold[j - 1]
b:=max_threshold[j - 1]
endif
*此处的beak是为了如果找到满足的圆就跳出这个for循环,不找了
break
endfor
if (Area<150000 or Area>450000)
continue
endif
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)
area_center (Circle, Area1, Row1, Column1)
break
endfor
if (a=6 and b=31)
dev_display (Image)
dev_display (Circle)
disp_message (WindowHandle, '该圆块是黄色', 'window', 0, 0, 'red', 'true')
disp_message (WindowHandle, '该圆块面积为:'+Area1, 'window', 25, 0, 'red', 'true')
disp_message (WindowHandle, '该圆块中心横纵坐标为:'+'('+Row1+','+Column1+')', 'window', 50, 0, 'red', 'true')
endif
if (a=45 and b=65)
dev_display (Image)
dev_display (Circle)
disp_message (WindowHandle, '该圆块是红色', 'window', 0, 0, 'red', 'true')
disp_message (WindowHandle, '该圆块面积为:'+Area1, 'window', 25, 0, 'red', 'true')
disp_message (WindowHandle, '该圆块中心横纵坐标为:'+'('+Row1+','+Column1+')', 'window', 50, 0, 'red', 'true')
endif
if (a=18 and b=47)
dev_display (Image)
dev_display (Circle)
disp_message (WindowHandle, '该圆块是蓝色', 'window', 0, 0, 'red', 'true')
disp_message (WindowHandle, '该圆块面积为:'+Area1, 'window', 25, 0, 'red', 'true')
disp_message (WindowHandle, '该圆块中心横纵坐标为:'+'('+Row1+','+Column1+')', 'window', 50, 0, 'red', 'true')
endif
catch (Exception)
endtry
stop()
endfor