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?
Asked
Active
Viewed 1,865 times
2 Answers
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.
-
yes it would. Your function works great. Maybe just translating into C++ would be sufficient... – patrickkidd Mar 17 '17 at 04:23
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