Halcon顏色識別

别动我的猫發表於2024-08-13

本文接掃halcon識別排序顏色,複雜點在於無法使用單一影像區域識別出5中顏色。這裡用到了ImageR 和 ImageS

*顏色識別


*定義顏色型別
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

相關文章