[英]QT QImage, how to extract RGB?
我想从 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()、qBlue() 和 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)
方法,因此您可以直接从图像像素中获取颜色信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.