如何从浮点数组创建一个新的QImage [英] how to create a new QImage from an array of floats
问题描述
我有一个表示Image的浮点数组。(第一列)。
我想在QGraphicsSecene上将图像显示为QPixmap。为了做到这一点,我尝试使用QImage构造函数从我的数组创建一个新图像 - QImage(const uchar * data,int width,int height,Format format)。
我首先创建了一个新的unsigned char并将我原始数组中的每个值转换为新的unsigned char one,然后尝试使用以下代码创建一个新图像:
I have an array of floats that represents an Image.(column first). I want to show the image on a QGraphicsSecene as a QPixmap. In order to do that I tried to create anew image from my array with the QImage constructor - QImage ( const uchar * data, int width, int height, Format format ). I first created a new unsigned char and casted every value from my original array to new unsigned char one, and then tried to create a new image with the following code:
unsigned char * data = new unsigned char[fres.length()];
for (int i =0; i < fres.length();i++)
data[i] = char(fres.dataPtr()[i]);
bcg = new QImage(data,fres.cols(),fres.rows(),1,QImage::Format_Mono);
问题在于我尝试以下列方式访问信息:
The problem is when I try to access the information in the following way:
bcg-> pixel(i,j);
bcg->pixel(i,j);
我只得到值12345.
如何创建一个我的数组中的可见图像。
谢谢
I get only the value 12345. How can I create a viewable image from my array. Thanks
推荐答案
这里有两个问题。
一,将 float
转换为 char
只需将 float $ c $舍入c>,因此0.3可以舍入为0,0.9可以舍入为
1
。对于0..1的范围, char
将仅包含0或1.
One, casting a float
to a char
simply rounds the float
, so 0.3 may be rounded to 0 and 0.9 may be rounded to 1
. For a range of 0..1, the char
will only contain 0 or 1.
为char提供全范围,使用乘法:
To give the char the full range, use a multiply:
data[i] = (unsigned char)(fres.dataPtr()[i] * 255);
(另外,您的演员表不正确。)
(Also, your cast was incorrect.)
另一个问题是你的 QImage :: Format
是不正确的; Format_Mono
期望1BPP bitpacked 数据,而不是您期望的8BPP。有两种方法可以解决此问题:
The other problem is that your QImage::Format
is incorrect; Format_Mono
expects 1BPP bitpacked data, not 8BPP as you're expecting. There are two ways to fix this issue:
// Build a colour table of grayscale
QByteArray data(fres.length());
for (int i = 0; i < fres.length(); ++i) {
data[i] = (unsigned char)(fres.dataPtr()[i] * 255);
}
QVector<QRgb> grayscale;
for (int i = 0; i < 256; ++i) {
grayscale.append(qRgb(i, i, i));
}
QImage image(data.constData(), fres.cols(), fres.rows(), QImage::Format_Index8);
image.setColorTable(grayscale);
// Use RGBA directly
QByteArray data(fres.length() * 4);
for (int i = 0, j = 0; i < fres.length(); ++i, j += 4) {
data[j] = data[j + 1] = data[j + 2] = // R, G, B
(unsigned char)(fres.dataPtr()[i] * 255);
data[j + 4] = ~0; // Alpha
}
QImage image(data.constData(), fres.cols(), fres.rows(), QImage::Format_ARGB32_Premultiplied);
这篇关于如何从浮点数组创建一个新的QImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!