在Qt中用什么类来处理图片让其真彩色变成黑白色,或能让黑白色变成真彩色!
得到答案立即结贴!
------解决方案--------------------
[转载]qt编程图像灰度化改进与详细注释 (2012-08-03 22:53:27)转载▼
标签: 转载
原文地址:qt编程图像灰度化改进与详细注释作者:930154711
最近在使用qt研究图像处理,第一步必然是最基础的图像灰度化,由于初学qt,对qt图像处理这一块一点头绪也没有,此时只好百度!网络上有人介绍了,qt提供四种图像类型:QImage, QPixmap, QPicture, QBitmap, 根据qt 文档对这四种类型的解释,发现QImage正是我需要的类型,可以很方便地读取图像的像素信息。
接着继续百度qt如何灰度化图像,找到的代码有两种:
一种是使用color table的方法:
#include<QApplication>
02 #include<QLabel>
03 #include<QDebug>
04
05 const QString rgbFile("special.jpg");
06 const QString grayFile("gray.jpg");
07
08 static bool convertToGray();
09
10 int main(int argc,char *argv[])
11 {
12 QApplication app(argc,argv);
13 QLabel rgbLabel,grayLabel;
14
15 if(!convertToGray()){
16 return 1;
17 }
18
19 rgbLabel.setPixmap(QPixmap(rgbFile));
20 grayLabel.setPixmap(QPixmap(grayFile));
21 rgbLabel.show();
22 grayLabel.show();
23 return app.exec();
24 }
25
26 //转为灰度图
27 static bool convertToGray()
28 {
29 QImage rgbImage(rgbFile);
30 QSize size=rgbImage.size();
31 QImage grayImage(size,QImage::Format_Indexed8);
32 int width=size.width();
33 int height=size.height();
34 uchar * rgbImageData=rgbImage.bits();
35 uchar * grayImageData=grayImage.bits();
36
37 if(rgbImage.isGrayscale()){
38 qDebug()<<"Image is already gray!Conversion stopped!";
39 return false;
40 }
41
42 //若width不是4的倍数,会自动添加字节,使之对齐到4的倍数
43 int realWidth1=rgbImage.bytesPerLine();
44 int realWidth2=grayImage.bytesPerLine();
45 uchar * backup1=rgbImageData;
46 uchar * backup2=grayImageData;
47 //直接取用green绿色分量值作为gray索引值
48 for(int i=0;i<height;
49 i++,
50 rgbImageData=backup1+realWidth1*i,
51 grayImageData=backup2+realWidth2*i){
52 for(int j=0;j<width;j++){
53 *grayImageData=*(rgbImageData+1);
54 rgbImageData+=4;
55 grayImageData++;
56 }
57 }
58
59 QVector<QRgb> grayColorTable;
60 uint rgb=0;
61 for(int i=0;i<256;i++){
62 grayColorTable.append(rgb);
63 rgb+=0x00010101;//r,g,b值分别加1,a值不变,见QRgb说明
64 }
65
66 grayImage.setColorTable(grayColorTable);
67 grayImage.save(grayFile);
68 return true;
69 }
主要看static bool convertToGray() 方法的处理,很多人看不懂
52 for(int j=0;j<width;j++){
53 *grayImageData=*(rgbImageData+1);
54 rgbImageData+=4;
55 grayImageData++;