Tutorial :how to create a new QImage from an array of floats



Question:

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

I get only the value 12345. How can I create a viewable image from my array. Thanks


Solution:1

There are two problems here.

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.

To give the char the full range, use a multiply:

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

(Also, your cast was incorrect.)

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

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »