Qt生成灰度图




01

#include<QApplication>
02#include<QLabel>
03#include<QDebug>
04 
05const QString rgbFile("special.jpg");
06const QString grayFile("gray.jpg");
07 
08static bool convertToGray();
09 
10int 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//转为灰度图
27static 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}


Qt生成灰度图
http://blog.csdn.net/NRC_DouNingBo/archive/2010/10/09/5929106.aspx


http://www.oschina.net/code/snippet_96486_4027

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值