QT QImage,如何提取RGB

QT QImage, how to extract RGB?

本文关键字:提取 RGB 何提取 QImage QT      更新时间:2023-10-16

我想从QImage中的每个像素中提取RGB。理想情况下,我想使用img.bits()函数。

QImage img;
if( img.load("Red.jpg") )
{
    uchar *bits = img.bits();
    for (int i = 0; i < 12; i++)
    {
        std::cout << (int) bits[i] << std::endl;
    }
}

如何操作返回的位?我希望全是红色,因为图片是在Paint中创建的纯红色图像。然而,我得到了36、27、237、255、36等…

QImage img( "Red.jpg" );
if ( false == img.isNull() )
{
    QVector<QRgb> v = img.colorTable(); // returns a list of colors contained in the image's color table.
    for ( QVector<QRgb>::const_iterator it = v.begin(), itE = v.end(); it != itE; ++it )
    {
        QColor clrCurrent( *it );
        std::cout << "Red: " << clrCurrent.red()
                  << " Green: " << clrCurrent.green()
                  << " Blue: " << clrCurrent.blue()
                  << " Alpha: " << clrCurrent.alpha()
                  << std::endl;
    }
}

然而,上面的这个例子确实返回了颜色表。颜色表不包含两次相同的颜色。它们将按外观顺序添加一次
如果你想得到每个像素的颜色,你可以使用下一行:

for ( int row = 1; row < img.height() + 1; ++row )
    for ( int col = 1; col < img.width() + 1; ++col )
    {
        QColor clrCurrent( img.pixel( row, col ) );
        std::cout << "Pixel at [" << row << "," << col << "] contains color ("
                  << clrCurrent.red() << ", "
                  << clrCurrent.green() << ", "
                  << clrCurrent.blue() << ", "
                  << clrCurrent.alpha() << ")."
                  << std::endl;
    }

bits()的参考说明:

返回指向第一个像素数据的指针。这相当于scanLine(0)。

因此,如果您检查scanLine() 的参考

如果您正在访问32 bpp的图像数据,请将返回的指针强制转换为QRgb*(QRgb大小为32位),并使用它来读取/写入像素值。不能直接使用uchar*指针,因为像素格式取决于底层平台上的字节顺序。使用qRed()、qGreen()、qclue()和qAlpha()访问像素。

另一种选择可能是pixel()成员函数。

希望能有所帮助。

使用bits()函数的问题之一是需要知道原始图像的格式。您应该使用convertToFormat将其转换为RGB。

img = img.convertToFormat(QImage::Format_RGB888);

现在,当您调用bits()时,数据将采用RGB格式,并进行适当的数据对齐。

uchar *bits = img.bits();
for (int i = 0; i < (img.width() * img.height() * 3); i++)
{
    std::cout << (int) bits[i] << std::endl;
}

在Qt 5.6中引入了QColor QImage::pixelColor(int x, int y)方法,可以直接从图像像素中获取颜色信息。