4

If I have a QImage with an alpha channel, how can I create a new QImage which is cropped to the bounding box of the opaque area?

Daniel
  • 2,032
  • 5
  • 21
  • 27

2 Answers2

1

I found another SO answer (in C++) that does this:

Does Qt have a way to find bounding box of an image?

def bbox(p):
    bounding-box-of-an-image
    l = p.width()
    t = p.height()
    r = 0
    b = 0

    for y in range(p.height()):
        rowFilled = False
        for x in range(p.width()):
            if qAlpha(p.pixel(x, y)):
                rowFilled = True
                r = max(r, x)
                if l > x:
                    l = x
        if rowFilled:
            t = min(t, y)
            b = y
    return QRect(QPoint(l, t), QPoint(r, b))

but it would be great if there were a better/faster way to do this.

Community
  • 1
  • 1
Daniel
  • 2,032
  • 5
  • 21
  • 27
1

What you are trying to achieve is part of image processing. Which is not the standard operation in QImage. You have to walk through the pixels and calculate your bounding box. I'd suggest you to use cv libs coz they are good for such operations.

G Sree Teja Simha
  • 495
  • 1
  • 6
  • 15