[Qt + OpenCV] Displaying Images and Convert to Grayscale

If you are interested to just display the image, see displaying image in Qt with OpenCV.
1. Create a new Qt GUI Application project.
2. Add a new Label and 3 Push Buttons (Open Image, To Grayscale, and Reset buttons) in the form.
3. Do the rest with writing the program:



This is the header displaywin.h:
#ifndef DISPLAYWIN_H
#define DISPLAYWIN_H
#include <QMainWindow>
#include <opencv/cv.h>
#include <opencv/highgui.h>
namespace Ui {
class DisplayWin;
}

class DisplayWin : public QMainWindow
{
    Q_OBJECT
    
public:
    explicit DisplayWin(QWidget *parent = 0);
    ~DisplayWin();
    
private slots:
    void openImage();
    void toGrayscaleImg();
    void on_btnOpen_clicked();
    void on_btnReset_clicked();
    void on_btnToGray_clicked();

private:
    Ui::DisplayWin *ui;
    QString fileName;
    IplImage *iplImg;
    char* charFileName;
    QImage qimgNew;
    QImage qimgGray;
};

#endif // DISPLAYWIN_H
displaywin.cpp:
#include "displaywin.h"
#include "ui_displaywin.h"
#include <opencv2/opencv.hpp>
#include <QFileDialog>

DisplayWin::DisplayWin(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::DisplayWin)
{
    ui->setupUi(this);
}

DisplayWin::~DisplayWin()
{
    delete ui;
}

void DisplayWin::openImage()
{
    fileName = QFileDialog::getOpenFileName(this,tr("Open Image"),QDir::currentPath(),tr("Image Files [ *.jpg , *.jpeg , *.bmp , *.png , *.gif]"));
    charFileName = fileName.toLocal8Bit().data();
    iplImg = cvLoadImage(charFileName);
    qimgNew = QImage((const unsigned char*)iplImg->imageData,iplImg->width,iplImg->height,QImage::Format_RGB888).rgbSwapped();
    ui->lblImage->setPixmap(QPixmap::fromImage(qimgNew));
}
void DisplayWin::toGrayscaleImg()
{
    ui->lblImage->clear();
    IplImage *imgGray = cvLoadImage(charFileName, CV_LOAD_IMAGE_GRAYSCALE);
    qimgGray = QImage((const unsigned char*)imgGray->imageData,imgGray->width,imgGray->height,QImage::Format_Indexed8);
    qimgGray.setPixel(0,0,qRgb(0,0,0));
    ui->lblImage->setPixmap(QPixmap::fromImage(qimgGray));
}
void DisplayWin::on_btnOpen_clicked()
{
    openImage();
}
void DisplayWin::on_btnReset_clicked()
{
    ui->lblImage->clear();
}

void DisplayWin::on_btnToGray_clicked()
{
    toGrayscaleImg();
}
main.cpp:
#include "displaywin.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    DisplayWin w;
    w.show();
 
    return a.exec();
}
You can download the project here

2 comments:

  1. Hey. can you help me with my project? Badly needed. :'(
    It is all about Image Processing. How can I apply bicubic interpolation? Can you show me?

    ReplyDelete
  2. whoa! Thanks!
    worked for me, nice job. Very helpful.

    ReplyDelete