You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Halcon中合并区域数组中的重叠区域?

合并重叠矩形区域的代码问题

我正在遍历图中的所有矩形区域,想找出重叠的区域并将它们合并。我觉得问题出在区域数组的初始化上,之前看过一个类似的Stack Overflow问题,但它是关于图标变量的,和区域数组不相关。

尝试的代码:

* generated_rects is filled with 81 mostly overlapping rectangles
resultRegions := [] 
count_obj (generated_rects, nrOfRects)
for i := 0 to nrOfRects-1 by 1
    * get center
    region_features (generated_rects, 'row', r)
    region_features (generated_rects, 'column', c)     
    if (resultRegions == [])
        * copy region         
        continue
    endif
    * if there are result regions to check for overlap 
    count_obj (resultRegions, resultRegions_count) // error on: resultRegions
    for j := 0 to resultRegions_count -1 by 1
        select_obj (resultRegions, selectedRegion, j) // error on: resultRegions
        
        
        * get_region_index (resultRegions, r, c, Index) // error on: resultRegions
        * test_region_point (resultRegions, r, c, IsInside) // error on: resultRegions
    endfor    
endfor

重叠矩形示例


问题分析与修复

你的核心问题是错误地用元组语法初始化Halcon区域对象集合,Halcon里的区域对象集合(Iconic Object Tuple)不能用[]直接创建,必须用gen_empty_obj生成空对象集合,再通过concat_obj添加区域。另外原代码还有索引从0开始的错误(Halcon对象索引从1开始)。

修正后的代码

* generated_rects is filled with 81 mostly overlapping rectangles
gen_empty_obj (resultRegions)
count_obj (generated_rects, nrOfRects)

for i := 1 to nrOfRects by 1
    select_obj (generated_rects, currentRect, i)
    count_obj (resultRegions, resultCount)
    isOverlapped := False
    
    if resultCount > 0
        for j := 1 to resultCount by 1
            select_obj (resultRegions, existRect, j)
            * 判断两个区域是否重叠(交集面积大于0)
            intersection (currentRect, existRect, intersectRegion)
            area_center (intersectRegion, Area, _, _)
            if Area > 0
                * 合并重叠区域
                union2 (currentRect, existRect, mergedRegion)
                * 更新结果集合:移除原区域,添加合并后的区域
                concat_obj (resultRegions, mergedRegion, tempRegions)
                select_obj (tempRegions, resultRegions, [1:j-1, j+1:resultCount+1])
                isOverlapped := True
                break
            endif
        endfor
    endif
    
    * 无重叠则直接添加当前区域到结果集合
    if not isOverlapped
        concat_obj (resultRegions, currentRect, resultRegions)
    endif
endfor

关键要点

  1. 用gen_empty_obj初始化空区域集合,而非[]
  2. Halcon对象索引从1开始,避免用0导致select_obj报错
  3. 通过intersection+area_center判断区域是否重叠,用union2合并重叠区域
  4. 更新结果集合时要正确移除旧区域、添加合并后的新区域

内容的提问来源于stack exchange,提问作者Malinko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 05:03:21