C++ OpenCV利用Trackbar来滑动调节亮度

我把之前写的代码都放进了一个自定义类 TydCV 里面了,有点自恋哈哈。现在头文件 cv.hpp 长这样。

#include <opencv2/opencv.hpp>
#include <opencv2/opencv_modules.hpp>
#include <opencv2/dnn.hpp>
#include <opencv2/cudaarithm.hpp>
#include <opencv2/cudaoptflow.hpp>
#include <opencv2/cudaimgproc.hpp>
#include <opencv2/cudafeatures2d.hpp>
#include <opencv2/cudaobjdetect.hpp>
#include <opencv2/cudawarping.hpp>
#include <opencv2/cudafilters.hpp>
#include <bits/stdc++.h>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2\imgproc\types_c.h>

using namespace std;
using namespace cv;
using namespace cv::cuda;
using namespace cv::dnn;

class TydCV {
private:
    string IMG_PATH;
public:
    TydCV() {
        cout << "Built with OpenCV " << CV_VERSION << endl;
    }
    void deviceQuery(); //CUDA设备查询
    void colorSpace(Mat& image); //图像色彩空间转换
    void colorSpace(Mat& image, string filename); //图像色彩空间转换, 可保存图像
    void lightTrackbar(Mat& image);  //滚动条调节亮度
    ~TydCV() {
        waitKey(0);
        destroyAllWindows();
    }
};

然后新建一个源文件 lightTrackbar.cpp 用来实现头文件的 lightTrackbar 函数,代码如下:

#include "cv.hpp"

Mat src, dst, m;
int lightness;

static void on_track(int,void*) {
    m = Scalar(lightness, lightness, lightness);
    cv::add(src, m, dst);
    imshow("亮度调整", dst);
}

void TydCV::lightTrackbar(Mat& image) {
    namedWindow("亮度调整", WINDOW_AUTOSIZE);
    dst = Mat::zeros(image.size(),image.type());
    m = Mat::zeros(image.size(),image.type());
    src = image;
    int max_value = 100;
    lightness = 50;
    createTrackbar("Light Trackbar","亮度调整", &lightness, max_value, on_track);
    on_track(50,0);
}

最后在 main.cppmain 函数中调用,查看一下效果,注意这个不能打断点用Image Watch查看嗷!

#include "cv.hpp"
string IMG_PATH = "D:/Code/CppCode/OpencvProject/img/";

int main() {
    Mat lena = imread(IMG_PATH+"lena.png",1);
    TydCV demo;
    demo.lightTrackbar(lena);
    waitKey(0);
    return 0;
}