是否有一个函数来获得一个QImage的非白色区域的边界框

Is there a function to get the bounding box of the non-white area of a QImage?

本文关键字:QImage 一个 白色 边界 区域 函数 有一个 是否      更新时间:2023-10-16

我有一个QImage,我需要修剪周围的白色(即裁剪到非白色区域)。

QImage或QPixmap是否有一个内置函数,将返回图像的非白色区域的边界框,类似于QGraphicsPixmapItem::opaqueArea() ?也就是说,没有非白色像素在边界框之外。

我没有看到一个内置的函数,但它应该很容易让你自己的,像这样:

QRect getBoundsWithoutColor(QImage qImage, const Qcolor &exclusionColor = Qt:white)
{
    QRect ofTheKing;
    int maxX = 0; int minX = qImage.width;
    int maxY = 0; int minY = qImage.height;
    for(int x=0; x < qImage.width(); x++)
        for(int y=0; y < qImage.height(); y++)
            if (QColor.fromRgb(qImage.pixel(x, y)) != exclusionColor)
            {
                if(x < minX) minX = x;
                if(x > maxX) maxX = x;
                if(y < minY) minY = y;
                if(y > maxY) maxY = y;
            }
    if (minX > maxX || minY > maxY)
        // The whole picture is white. How you wanna handle this case is up to you.
    else
        ofTheKing.setCoords(minX, minY, maxX+1, maxY+1);
    return ofTheKing;
 }

QImage中没有内置这样的函数,但是由于QImage允许直接访问像素数据,所以自己编写代码应该不会太难。在我的脑海中,它可能看起来像这样。

const QRgb CROP_COLOR = QColor(Qt::white).rgb();
QImage crop(const QImage& image)
{
    QRect croppedRegion(0, 0, image.width(), image.height());
    // Top
    for (int row = 0; row < image.height(); row++) {
        for (int col = 0; col < image.width(); col++) {
            if (image.pixel(col, row) != CROP_COLOR) {
                croppedRegion.setTop(row);
                row = image.height();
                break;
            }
        }
    }
    // Bottom
    for (int row = image.height() - 1; row >= 0; row--) {
        for (int col = 0; col < image.width(); col++) {
            if (image.pixel(col, row) != CROP_COLOR) {
                croppedRegion.setBottom(row);
                row = -1;
                break;
            }
        }
    }
    // Left
    for (int col = 0; col < image.width(); col++) {
        for (int row = 0; row < image.height(); row++) {
            if (image.pixel(col, row) != CROP_COLOR) {
                croppedRegion.setLeft(col);
                col = image.width();
                break;
            }
        }
    }
    // Right
    for (int col = image.width(); col >= 0; col--) {
        for (int row = 0; row < image.height(); row++) {
            if (image.pixel(col, row) != CROP_COLOR) {
                croppedRegion.setRight(col);
                col = -1;
                break;
            }
        }
    }
    return image.copy(croppedRegion);
}

免责声明:此代码可能可以优化。我还没有测试它,它看起来可以编译,但可能有一个错别字。我把它放在这里只是为了说明大意