tags:

views:

91

answers:

1

Hi all, 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

+3  A: 

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);
strager
HI,thanks for the reply but, your second reply does not compile.there is no constructor for QImage that receives a QByteArray.So I've changed it to the following: unsigned char * c_data = new unsigned char[fres.length() * 4]; for (int i = 0, j = 0; i < fres.length(); ++i, j += 4) { c_data[j] = c_data[j + 1] = c_data[j + 2] =(unsigned char)(fres.dataPtr()[i] * 255); c_data[j + 4] = ~0; }QImage image(c_data, fres.cols(), fres.rows(), QImage::Format_ARGB32_Premultiplied);And Still the image does not display properly.(all is black and not all the pixel values are 0).
boaz shor
@boaz shor, Sorry about it not compiling; calling `.constData()` on `data` should fix that. I'm not sure what else could be the problem; have you tried the indexed (grayscale) version?
strager