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:
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);
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] =
(unsigned char)(fres.dataPtr()[i] * 255);
data[j + 4] = ~0;
}
QImage image(data.constData(), fres.cols(), fres.rows(), QImage::Format_ARGB32_Premultiplied);
source
share