如何在图像提取条码区域
以快递上的一维码为例,由于快递标签处有很多的文字,符号和边框,增大了定位的难度。(如下图)而且有很多噪声的影响。
halcon实现:
1,读入图像,提取轮廓
有两种方法:
基于边缘提取
blob分析
read_image (Image, 'C:/Users/86175/Desktop/4.png')
get_image_size (Image, Width, Height)
dev_open_window (0, 0, Width/2, Height/2, 'black', WindowHandle)
dev_display (Image)
rgb1_to_gray (Image, GrayImage)
*第一种边缘提取初步提取轮廓
laplace_of_gauss(GrayImage, ImageLaplace, 2)//拉布拉斯算子
threshold(ImageLaplace, Region3, 5, 127)
skeleton(Region3, Skeleton3)
connection (Skeleton3, ConnectedRegions2)
select_shape (ConnectedRegions2, SelectedRegions, ['area','width','height'], 'and', [0,0,0], [220,80,200])
*第二种Blob分析法初步提取条码
threshold (GrayImage, Regions, 7, 107)
connection (Regions, ConnectedRegions)
二者提取效果差不多,但是考虑到Blob分析法可能对相机像素有较大的要求,否则二值化后可能提取不出条码线,个人觉得用边缘提取的方式较稳定。
2,筛选条码区域
*通过面积和矩形度筛选
select_shape (ConnectedRegions, SelectedRegions1, 'area', 'and', 60, 1500)
select_shape_std (SelectedRegions1, SelectedRegions, 'rectangle2', 60)
*提取轮廓
union1 (SelectedRegions, RegionUnion)
skeleton (RegionUnion, Skeleton4)
gen_contours_skeleton_xld (Skeleton4, Contours1, 1, 'filter')
*通过轮廓长度过滤小噪声
select_contours_xld (Contours1, SelectedContours, 'contour_length', 30, 200, -0.5, 0.5)
3,拟合直线,进一步筛选
*因为条码都是直线,可以通过角度相同的直线分割条码
*拟合直线
fit_line_contour_xld (SelectedContours, 'tukey', -1, 0, 5, 2, RowBegin, ColBegin, RowEnd, ColEnd, Nr, Nc, Dist1)
*画拟合线
gen_region_line (RegionLines1, RowBegin, ColBegin, RowEnd, ColEnd)
*在0~-180°里每-30°查找一次条码
for i:=-1 to -150 by -30
select_shape (RegionLines1, SelectedRegions3, 'phi', 'and', rad(i-30), rad(i))
count_obj (SelectedRegions3, Number)
if(Number>12)
union1 (SelectedRegions3, RegionUnion1)
area_center (RegionUnion1, Area1, Row, Column)
orientation_region (RegionUnion1, Phi)
if(Phi>rad(90))
Phi:=Phi-rad(180)
endif
if(Phi<-rad(90))
Phi:=rad(180)+Phi
endif
vector_angle_to_rigid (Row, Column, Phi, Row, Column,rad(0), HomMat2D)
affine_trans_region (RegionUnion1, RegionAffineTrans1, HomMat2D, 'nearest_neighbor')
affine_trans_image (GrayImage, ImageAffineTrans, HomMat2D, 'constant', 'false')
closing_rectangle1 (RegionAffineTrans1, RegionClosing, 80, 2)
connection (RegionClosing, ConnectedRegions1)
select_shape (ConnectedRegions1, SelectedRegions4, 'area', 'and', 2954.26, 50000)
shape_trans (SelectedRegions4, RegionTrans, 'rectangle2')
region_features (RegionTrans, 'width', w)
region_features (RegionTrans, 'height', h)
if(w/h<2.5 or w/h>10)
continue
endif
reduce_domain (ImageAffineTrans, RegionTrans, ImageReduced1)
threshold (ImageReduced1, Regions1, 160, 254)
area_center (Regions1, Area, Row1, Column1)
threshold (ImageReduced1, Regions2, 0, 120)
area_center (Regions2, Area2, Row2, Column2)
if(Area>Area2)
if(Area/Area2>2)
continue
endif
endif
if(Area2>Area)
if(Area2/Area>2)
continue
endif
endif
dilation_circle (RegionTrans, RegionDilation, 6)
reduce_domain (ImageAffineTrans, RegionDilation, ImageReduced)
endif
endfor
版权所有:江苏和讯自动化设备有限公司所有 备案号:苏ICP备2022010314号-1
技术支持: 易动力网络