QT中RGB转灰度图像
QImage ToGrayImage_triggered(QImage m_QImage)
{
QSize size=m_QImage.size();
QImage m_QGrayImage = QImage(size,QImage::Format_Indexed8);
int width=size.width();
int height=size.height();
uchar * rgbImageData=m_QImage.bits();
uchar * grayImageData=m_QGrayImage.bits();
if(m_QImage.allGray())
{
m_QGrayImage = QImage(m_QImage);
//qDebug()<<"Image is already gray!Conversion stopped!";
return ;
}
//若width不是4的倍数,会自动添加字节,使之对齐到4的倍数
int realWidth1=m_QImage.bytesPerLine();
int realWidth2=m_QGrayImage.bytesPerLine();
uchar * backup1=rgbImageData;
uchar * backup2=grayImageData;
for(int i=0;i<height;i++)
{
for(int j=0;j<width;j++)
{
uchar R = *rgbImageData;
uchar G = *(rgbImageData+1);
uchar B = *(rgbImageData+2);
*grayImageData=(uchar)(0.29900*R + 0.58700*G + 0.11400*B);
rgbImageData+=3;
grayImageData++;
}
rgbImageData=backup1+realWidth1*i;
grayImageData=backup2+realWidth2*i;
}
return m_QGrayImage;
}