【QT】彩色轉單色


【目的】

  1. 顯示兩張圖片,左邊為原圖,右邊為原圖的單色圖。

【程式】

#include <QApplication>
#include <QWidget>
#include <QPainter>
#include <QBitmap>
#include <QImage>
#include <QColor>

class PainterWidget : public QWidget {
protected:
    void paintEvent(QPaintEvent*);
};

void PainterWidget::paintEvent(QPaintEvent *event) {
    QImage img("lena_std.png");
    QImage org = img;
    QRgb value;
    QPainter painter(this);

    for (int dx=0; dx < img.width(); dx++)
    {
      for (int dy=0; dy < img.height(); dy++)
      {
        value = img.pixel(dx ,dy);
        int r = qRed(value);
        int g = qGreen(value);
        int b = qBlue(value);

        int a = (int)((r + g + b)/3);
        if (a>0x7f) {a=0xff;}
        else {a=0x00;}
        value = qRgb(a, a, a);
        img.setPixel(dx, dy, value);
      }
    }
    painter.drawImage(0, 0, org);
    painter.drawImage(0+org.width(), 0, img);

}

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);
    PainterWidget pWidget;
    pWidget.setWindowTitle("QImage Demo");
    pWidget.resize(600, 300);
    pWidget.show();
    return app.exec();
}

 

【結果】

image

【參考】

 

Ed32. Copyright 2008 All Rights Reserved Revolution Two Church theme by Brian Gardner Converted into Blogger Template by Bloganol dot com