Qt creator5.7 OpenCV249之图片灰度处理(含源码下载)

来源:互联网 发布:江津加工中心编程招聘 编辑:程序博客网 时间:2024/04/28 12:20

我们先来看程序运行:




先了解下原理:

图像灰度化是指将彩色图片处理为256级的灰度图像。

公式为Gray=x*R+y*G+z*B

Gray是当前像素的灰度值,x,y,z 是系数,R,G,B表示红绿蓝

一般表示为:

Gray=0.299*R+0.587*G+0.144*B

实际上为了方便可以这样:

Gray=(R+G+B)/3


Opencv里面的函数如下:

void cv::cvtColor(

InputArray src,

OutputArray dst,

int code,

int dstCn=0);

dstCn我们采用默认值就可以了。

code呢?

在一般的c++里面采用COLOR_RGB2GRAY

在Qt里面用COLOR_BGR2GRAY


还有一个要注意的地方:



QImage::Format_Grayscale8
24
The image is stored using an 8-bit grayscale format.


当我们要把灰度图像用QImage读取时,要设置此方式:

下面是源码打包下载地址:

http://download.csdn.net/detail/qq78442761/9778008

下面是程序源码

widget.h

#ifndef WIDGET_H#define WIDGET_H#include <QWidget>#include <QMessageBox>#include <QImage>#include <opencv2/core/core.hpp>#include <opencv2/highgui/highgui.hpp>#include <opencv2/imgproc/imgproc.hpp>namespace Ui {class Widget;}class Widget : public QWidget{    Q_OBJECTpublic:    explicit Widget(QWidget *parent = 0);    ~Widget();    cv::Mat srcImage,dstImage,tempImage;    QImage img;private slots:    void on_pushButton_clicked();private:    Ui::Widget *ui;};#endif // WIDGET_H

widget.cpp

#include "widget.h"#include "ui_widget.h"Widget::Widget(QWidget *parent) :    QWidget(parent),    ui(new Ui::Widget){    ui->setupUi(this);    setWindowTitle(tr("图像灰度处理"));    setMaximumSize(626,351);    srcImage=cv::imread("dog.jpg");    if(!srcImage.data)    {        QMessageBox megBox;        megBox.setText(tr("图片读取失败"));        megBox.exec();    }    else    {        //把原始图像载入进第一个label并且显示        cv::cvtColor(srcImage,srcImage,CV_BGR2RGB);        img=QImage((const unsigned char*)(srcImage.data),srcImage.cols,srcImage.rows,srcImage.cols*srcImage.channels(),QImage::Format_RGB888);        ui->label->clear();        img=img.scaled(ui->label->size());        ui->label->setPixmap(QPixmap::fromImage(img));    }    connect(ui->pushButton,SIGNAL(clicked(bool)),this,SLOT(on_pushButton_clicked()));}void Widget::on_pushButton_clicked(){    cv::cvtColor(srcImage,dstImage,cv::COLOR_BGR2GRAY);    //cv::imshow("test",dstImage);    img=QImage((const unsigned char*)(dstImage.data),dstImage.cols,dstImage.rows,dstImage.cols*dstImage.channels(),               QImage::Format_Grayscale8);    img=img.scaled(ui->label_2->size());    ui->label_2->setPixmap(QPixmap::fromImage(img));}Widget::~Widget(){    delete ui;}
main.cpp

#include "widget.h"#include <QApplication>int main(int argc, char *argv[]){    QApplication a(argc, argv);    Widget w;    w.show();    return a.exec();}



1 0
原创粉丝点击