计算任意基于像素的绘图的边界框

时间:2012-03-24 13:33:52

标签: graphics pixels bounding-box aabb

给定任意像素的连续绘制(例如在HTML5 Canvas上)是否有任何算法可以找到比简单looking at every pixel and recording the min/max x/y values更有效的轴对齐边界框?

3 个答案:

答案 0 :(得分:8)

只需扫描线从左上到右,然后向下移动以获得y顶部,以及类似的算法,其余方向不同。


由Phrogz编辑:

这是一个伪代码实现。包含的优化可确保每条扫描线不会查看早期传递所覆盖的像素:

function boundingBox()
  w = getWidth()            # Assuming graphics address goes from [0,w)
  h = getHeight()           # Assuming graphics address goes from [0,h)
  for y=h-1 to 0 by -1      # Iterate from last row upwards
    for x=w-1 to 0 by -1    # Iterate across the entire row
      if pxAt(x,y) then
        maxY=y
        break               # Break out of both loops

  if maxY===undefined then  # No pixels, no bounding box
    return               

  for x=w-1 to 0 by -1      # Iterate from last column to first
    for y=0 to maxY         # Iterate down the column, up to maxY
      if pxAt(x,y) then
        maxX=x
        break               # Break out of both loops

  for x=0 to maxX           # Iterate from first column to maxX
    for y=0 to maxY         # Iterate down the column, up to maxY
      if pxAt(x,y) then
        minX=x
        break               # Break out of both loops

  for y=0 to maxY           # Iterate down the rows, up to maxY
    for x=0 to maxX         # Iterate across the row, up to maxX
      if pxAt(x,y) then
        minY=y
        break               # Break out of both loops

  return minX, minY, maxX, maxY

结果(在实践中)与单个像素的蛮力算法大致相同,并且随着对象变大而显着提高。

演示:http://phrogz.net/tmp/canvas_bounding_box2.html

为了好玩,以下是该算法如何工作的直观表示:

enter image description here
enter image description here
enter image description here
enter image description here
enter image description here

按照您选择的方式执行两侧操作并不重要,您只需要确保将先前的结果考虑在内,这样就不会对角落进行双重扫描。

答案 1 :(得分:1)

您可以使用某种二进制搜索,或者在粗网格上采样,然后是连续更精细的网格。此方法的正确性取决于图形中是否允许“孔洞”。

答案 2 :(得分:0)

我不喜欢当前的答案。这是我插入OP网站的代码。在Firefox和Chrome中,速度要快得多。

这个想法是检查x轴上的所有像素,以查看Y轴上是否有命中。如果是这样,请更新Y并增加X,以便我们可以扫描最大X

function contextBoundingBox(ctx,alphaThreshold){
    if (alphaThreshold===undefined) alphaThreshold = 15;
    var w=ctx.canvas.width,h=ctx.canvas.height;
    var data = ctx.getImageData(0,0,w,h).data;

    let minX=w;
    let maxX=0
    let minY=h
    let maxY=0
    for(let y=0; y<h; y++)
    {
        for(let x=0; x<w; x++)
        {
            if (data[y*w*4 + x*4+3])
            {
                minX = Math.min(minX, x);
                maxX = Math.max(maxX, x);
                minY = Math.min(minY, y);
                maxY = y;
                x=maxX
            }
        }
    }

    return {x:minX,y:minY,maxX:maxX,maxY:maxY,w:maxX-minX,h:maxY-minY};
}
相关问题