Halcon選擇一堆region中面積第N大的region的算法實現

以下圖爲例:

比如我想把面積第2小的那個“小正方形”選擇出來,算法代碼如下:

複製代碼

1 read_image (Yuan, 'C:/Users/happy xia/Desktop/yuan.png')
2 binary_threshold (Yuan, Region, 'max_separability', 'dark', UsedThreshold)
3 connection (Region, ConnectedRegions)
4 area_center (ConnectedRegions, Area, Row, Column)
5 tuple_sort_index (Area, Indices)
6 Num := |Indices|
7 select_obj (ConnectedRegions, ObjectSelected, Indices[1] + 1)

複製代碼

 

該實現算法的關鍵是對算子tuple_sort_index意思的理解。

 

代碼中:

Area := [420, 12922, 38019, 58, 2033]

Indices := [3, 0, 4, 1, 2]

 

tuple_sort_index (Area, Indices)的意思是:先將Area中各元素按升序排序,然後將排序後的每一個Area分別在原Area元組中的索引放在元組Indices 中。

 

[3, 0, 4, 1, 2]的意思是:

58是Area 中的3號元素(元組索引從0開始)

420是Area 中的0號元素;

2033是Area 中的4號元素;

12922是Area 中的1號元素;

38019是Area 中的2號元素。

 

再看看上面tuple_sort_index算子的意思,可知Indices[1]面積第2小的元素在原Area元組中的索引,即索引是0。由於對於算子select_obj 來說,它的索引是從1開始的。所以Indices[1] + 1 是最終的索引。

 

結果圖:

 

如果要找到面積第二大的,只需將最後一句改爲:

select_obj (ConnectedRegions, ObjectSelected, Indices[Num -2] + 1)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章