How to create a new QImage from an array of floats

I have a float array that represents an image. (column first). I want to display the image on QGraphicsSecene as a QPixmap. To do this, I tried to create a new image from my array using the QImage constructor - QImage (const uchar * data, int width, int height, Format format). First, I created a new unsigned char and laid out each value from my original array into a 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 that I am trying to access the information as follows:

bcg-> pixels (I, J);

I get only the value 12345. How to create a visible image from my array. Thanks

+5
source share
1 answer

There are two problems here.

One, dropping a floatto a char, simply rounds float, so a value of 0.3 can be rounded to 0 and 0.9 can be rounded to 1. For a range of 0..1 charwill contain only 0 or 1.

To give char the full range, use multiply:

data[i] = (unsigned char)(fres.dataPtr()[i] * 255);

(Also, your lineup was incorrect.)

Another problem is that yours is QImage::Formatwrong; Format_Monoexpects 1BPP bitpacked data, not 8BPP, as you expect. There are two ways to fix this problem:

// 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);
+4
source

All Articles