Get raw data from QImage
I have a QImage that I built from a pixmap something like the following:
QPixmap fullPmap = topItem->pixmap();
fullPmap = fullPmap.copy(isec.toRect());
QImage chip = fullPmap.toImage();
This is basically intersecting with a rectangle on screen to crop the image to a chipped size.
I now need to get the character array representing that data back from chip.
How can I do this?
I tried something like this:
unsigned char * data = chip.bits();
And when I display "data" I get a completely distorted image, nothing like my actual chip.
fullPmap is an RGB image if that matters. I have some code that I am using to convert it to grayscale:
QRgb col;
int gray;
for (int i = 0; i < chip.width(); ++i)
{
for (int j = 0; j < chip.height(); ++j)
{
col = chip.pixel(i, j);
gray = qGray(col);
chip.setPixel(i, j, qRgb(gray, gray, gray));
}
}
Which I don'开发者_JAVA技巧t really like, but it seemed like the easiest way to do such a thing.
Displaying the data that is returned from bits() looks like this:
imwidth = chip.width();
imheight = chip.height();
QImage *qi = new QImage(imwidth, imheight, QImage::Format_RGB32);
// #pragma omp parallel for
for (int i = 0 ; i < imheight ; i++)
for (int j = 0 ; j < imwidth ; j++)
{
qi->setPixel(j,i,qRgb(data[i*imwidth + j],data[i*imwidth + j],data[i*imwidth + j]));
}
When dealing with raw image data, you need to be aware of some basic issues:
What is the format or layout of pixel data. The QImage converted from QPixmap is not necessarily always in RGB888 or RGB32. Call QImage::format() and deal with different layout differently. Especially with RGB32 family, you need to make sure you access them in right byte order (endian).
The bytes are not always layout exactly that many bytes to hold the pixels of the line. Typically a line will have more bytes than it's needed. Use QImage::bytesPerLine() to find out and advance the pointer by that many bytes when going to the next line. This is probably your issue in the building of the display image.
QImage::pixel() and setPixel() are really slow. Get/set pixel values from raw pixel buffer if possible.
This worked for me:
m_image = new QImage(IMAGE_WIDTH,IMAGE_HEIGHT, QImage::Format_RGB32);
m_image->fill(Qt::white);
int rawDataCount = 0;
for (int y = 0;y<IMAGE_HEIGHT;y++)
{
uint* line = (uint*)m_image->scanLine(y);
for (int x=0;x<IMAGE_WIDTH;x++)
{
WORD temp = cameraZero[rawDataCount++];
BYTE value = temp >> 2;
QColor grey(value,value,value);
line[x] = qRgba(value,value,value,100);
}
}
where cameraZero holds a list of pixel values.
精彩评论