Qt有办法找到图像的边界框吗?

ret*_*ile 8 qt

给定.png具有透明背景的图像,我想找到非透明数据的边界框.使用嵌套for循环QImage.pixel()非常缓慢.有没有在Qt中执行此操作的内置方法?

Arn*_*nce 5

有一个选项涉及使用 aQGraphicsPixmapItem并查询不透明区域 ( QGraphicsPixmapItem::opaqueArea().boundingRect())的边界框。不确定它是否是最好的方法,但它有效:) 可能值得深入研究 Qt 的源代码,看看它的核心代码是什么。

以下代码将打印出图像的宽度和高度,然后是图像不透明部分的宽度和高度:

QPixmap p("image.png");
QGraphicsPixmapItem *item = new QGraphicsPixmapItem(p);
std::cout << item->boundingRect().width() << "," << item->boundingRect().height() << std::endl;
std::cout << item->opaqueArea().boundingRect().width() << "," << item->opaqueArea().boundingRect().height() << std::endl;
Run Code Online (Sandbox Code Playgroud)


ypn*_*nos 4

如果 Pixel() 对您来说太慢,请考虑更有效的行数据寻址,给定 QImage p:

int l =p.width(), r = 0, t = p.height(), b = 0;
for (int y = 0; y < p.height(); ++y) {
    QRgb *row = (QRgb*)p.scanLine(y);
    bool rowFilled = false;
    for (int x = 0; x < p.width(); ++x) {
        if (qAlpha(row[x])) {
            rowFilled = true;
            r = std::max(r, x);
            if (l > x) {
                l = x;
                x = r; // shortcut to only search for new right bound from here
            }
        }
    }
    if (rowFilled) {
        t = std::min(t, y);
        b = y;
    }
}
Run Code Online (Sandbox Code Playgroud)

我怀疑它会比这更快。