之前博文格式已经固定,这里就不在赘述了,直接把核心代码进行解释一下即可,仅作为小笔记而已
项目实现功能:
按下键盘0,显示原始图像
按下键盘1,显示原始图像的灰度图
按下键盘2,显示原始图像的HSV色域空间
按下键盘3,显示原始图像像素点全部增加50
一、头文件
定义接口
头文件名称:key.h
#pragma once
#include<opencv2/opencv.hpp>using namespace cv;class KeyDemo {public:void key_response(Mat& image);
};
二、函数实现
#include"key.h"
,导入头文件,调用接口
namedWindow("response", WINDOW_FREERATIO);
,起一个新窗口用于展示结果
Mat result = Mat::zeros(image.size(), image.type());
,定义一个全为0和原图大小规格一样的图片,对象为result,初始化为全0的黑色图片
在ASCII编码中键盘上的按键其中数字0对应48,数字1对应49,数字2对应50,数字3对应51,ESC对应27
#include"key.h"
#include <iostream>
#include <opencv2/opencv.hpp>void KeyDemo::key_response(Mat& image) {namedWindow("response", WINDOW_FREERATIO);Mat result = Mat::zeros(image.size(), image.type());std::cout << "please select your key:" << std::endl;std::cout << "0 is origin\n1 is GRAY\n2 is HSV\n3 is light\n" << std::endl;while (true) {int c = waitKey(200);if (c == 27) {break;}if (c == 48) {std::cout << "enter is 0、";result = image;}if (c == 49) {std::cout << "enter is 1、";cvtColor(image,result,COLOR_BGR2GRAY);}if (c == 50) {std::cout << "enter is 2、";cvtColor(image, result, COLOR_BGR2HSV);}if (c == 51) {std::cout << "enter is 3、";result = Scalar(50,50,50);add(image, result, result);}imshow("response", result);}}
三、主函数
#include <opencv2/opencv.hpp>
#include <iostream>
#include "key.h"using namespace cv;
using namespace std;int main(int argc, char** argv) {Mat src = cv::imread("E:/C++_workspace/beyond.jpg", IMREAD_COLOR);if (src.empty()) {printf("load image is false...\n");return -1;}namedWindow("yanyu", WINDOW_FREERATIO);imshow("yanyu", src);KeyDemo yy;yy.key_response(src);waitKey(0);destroyAllWindows();return 0;
}
项目结构如图所示:
运行效果如下: