Halcon颜色识别

 

本文介绍halcon识别排线颜色,复杂点在于无法使用单一图像区域识同时别出5种颜色。这里用到了ImageR 和 ImageS两个通道拆分实现。

本篇共分为3个部分,详见代码注释:

  1.用单通道图像ImageR 识别 黑、棕、红 三种颜色

  2.转HSV通道,用IamgeS对比和ImageH识别出 粉红、黄色

  3.统一显示颜色坐标信息,美观

*颜色识别


*定义颜色类型
FushColor := ['black','brown','red','pink','yellow']

*颜色对应灰度值
HueRange := [10,51,68,100,145,191,\
             0,10,30,50]

*定义获取到的坐标,展示颜色
Address :=[]


*读取图片
read_image (Image, 'D:/hoclan/Color/cable1.png')

*分割成三通道,拆分成RGB三种单颜色的图片
decompose3 (Image, \
            ImageR, ImageG, ImageB)


*1.识别前面3种颜色 黑、棕、红
*知识点:彩色图片也可以二值化
*观察发现ImageR比较适合区分 黑、棕、红三色

*剪切
reduce_domain (ImageR, ImageR, ImageReduced)

*获取窗口句柄
dev_get_window (WindowHandle)

*遍历次数,通过样品的个数循环
* tuple_length (FushColor, Length)
Length := |FushColor|
for Index := 0 to 2 by 1
    *二值化 色调区间段进行颜色识别
    threshold (ImageReduced, Region1, \
               HueRange[Index*2], HueRange[Index*2+1])
    *区域填充(孔洞填充)
    *fill_up (Region1, RegionFillUp)
    *连通分割
    connection (Region1, ConnectedRegions)
    * 特征检测到目标区域 6585
    * 按照面积筛序 4421 4731 3400 
    select_shape (ConnectedRegions, SelectedRegions, 'area', 'and', 3000, 5000)
    *获取位置
    area_center (SelectedRegions, Area, Row, Column)
    
    Address[Index*2] := Row
    Address[Index*2+1] := Column
    *显示信息
    disp_message (WindowHandle, FushColor[Index], 'image', Row, Column, 'black', 'true')
endfor

*2.图像转HSV,用其对图像颜色的敏感来识别 pink 、 yellow
*图像转HSV
trans_from_rgb (ImageR, ImageG, ImageB, \
                ImageH, ImageS, ImageV, 'hsv')

*二值化,观察发现ImageS比较容易区分
threshold (ImageS, Region1, 100, 255)


*图像剪切 从色调ImageH 上进行剪切
* 色调H 才适合进行识别
reduce_domain (ImageH, Region1, ImageReduced)

*遍历次数,通过样品的个数循环
* tuple_length (FushColor, Length)
Length := |FushColor|
for Index := 3 to 4 by 1
    *二值化 色调区间段进行颜色识别
    threshold (ImageReduced, Region1, \
               HueRange[Index*2], HueRange[Index*2+1])
    *区域填充(孔洞填充)
    *fill_up (Region1, RegionFillUp)
    *连通分割
    connection (Region1, ConnectedRegions)
    * 特征检测到目标区域 6585
    * 按照面积筛序 4421 4731 3400 2615 
    select_shape (ConnectedRegions, SelectedRegions, 'area', 'and', 2500, 5000)
    *获取位置
    area_center (SelectedRegions, Area, Row, Column)
    
    Address[Index*2] := Row
    Address[Index*2+1] := Column
    *显示信息
    disp_message (WindowHandle, FushColor[Index], 'image', Row, Column, 'black', 'true')
endfor

*3.清空前面的模糊图像,展示颜色对应的坐标
dev_clear_window ()
reduce_domain (Image, Image, ImageReduced)

Length := |FushColor|
for Index := 0 to Length-1 by 1
    *显示信息
    disp_message (WindowHandle, FushColor[Index], 'image', Address[Index*2], Address[Index*2+1], 'black', 'true')
endfor

 

posted @ 2024-08-13 14:14  别动我的猫  阅读(227)  评论(0编辑  收藏  举报