QT QImage,如何提取RGB?

时间:2012-09-12 06:25:31

标签: c++ qt qimage

我想从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等......

4 个答案:

答案 0 :(得分:15)

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

答案 1 :(得分:6)

Reference for bits()说:

  

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

因此,如果您选中reference for scanLine()

  

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

另一个选项可能是pixel()成员函数。

希望有所帮助。

答案 2 :(得分:4)

使用bits()函数的一个问题是您需要知道原始图像的format。您应该使用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;
}

答案 3 :(得分:0)

在Qt 5.6中引入了pg_column_size(json_column) desc limit 1方法,因此您可以直接从图像像素获取颜色信息。

相关问题