QT QImage pixel manipulation

2019-02-08 11:56发布

I am building a QT GUI application and use QImage for opening images. My problem is that I can't figure out how to use QImage's bit() and scanline() methods to get access at per pixel level.

I've seen this post Qt QImage pixel manipulation problems but this is only for the first pixel of each row. Is this correct or I got it all wrong?

thanks in advance

3条回答
爷的心禁止访问
2楼-- · 2019-02-08 12:22

The answer did not work for me. It looks like, the data is not 32bit aligned on my system. To get the correct data, on my system i had to do this:

for(uint32_t Y = 0; Y < mHeight; ++Y)
{
    uint8_t* pPixel = Image.scanLine(Y);

    for(uint32_t X = 0; X < mWidth; ++X)
    {
      const int Blue = *pPixel++;
      const int Green = *pPixel++;
      const int Red = *pPixel++;

      uint8_t GrayscalePixel = (0.21f * Red) + (0.72f * Green) + (0.07 * Blue);
    }
}
查看更多
姐就是有狂的资本
3楼-- · 2019-02-08 12:23

It may not be immediately obvious from Kaleb's post, but the following works for setting a pixel on a Format_RGB32 image.

// Get the line we want
QRgb *line = (QRgb *)image->scanLine(row_index);

// Go to the pixel we want
line += col_index;

// Actually set the pixel
*line = qRgb(qRed(color), qGreen(color), qBlue(color));
查看更多
劫难
4楼-- · 2019-02-08 12:39

The scanlines correspond to the the height of image, the columns correspond to the width of the image.

According to the docs, the prototype looks like uchar* QImage::scanline(int i), or a similar const version.

But, as a commenter pointed out, because the data is dependent on the machine architecture and image, you should NOT use the uchar * directly. Instead, use something like the following:

QRgb *rowData = (QRgb*)img.scanLine(row);
QRgb pixelData = rowData[col];
int red = qRed(pixelData);
查看更多
登录 后发表回答