2

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

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

4

2 回答 2

4

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

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;
 }
于 2013-01-04T18:28:22.050 回答
1

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);
}

免责声明:此代码可能可以优化。我还没有测试它,它看起来像它编译但可能有一个错字。我只是把它放在那里以显示总体思路。

于 2013-01-04T18:22:32.640 回答