通过键盘来控制图片显示。
需要注意,按键是针对窗体的,而非控制台。
当按下按键 1 时,窗体显示灰度图像。
当按下按键 2 时,窗体显示HSV色彩格式图像。
当按下按键 3 时,窗体显示亮度不同的图像(固定亮度)。
当按下ESC时(两次),窗体退出。按两次是因为,第一次退出死循环,第二次是退出程序。
07_opencv_mat.h
#pragma once #ifndef _07_OPENCV_MAT_H #define _07_OPENCV_MAT_H #includeusing namespace cv; class QuickDemo { public: //滚动条 void keyboard_demo(Mat& image); }; #endif
07_opencv_mat.c
#include#include "07_opencv_mat.h" using namespace std; void QuickDemo::keyboard_demo(Mat &image) { Mat dst = image; Mat temp = Mat::zeros(image.size(), image.type()); while (true) { int c = waitKey(300); if (c == 27) // 按下 ESC 退出 { std::cout << "you enter key #ESC" << endl; break; } switch (c) { case 49: {// 按下 1 cvtColor(image, dst, COLOR_BGR2GRAY); std::cout << "you enter key #1" << endl; break; } case 50: {// 按下 2 cvtColor(image, dst, COLOR_BGR2HSV); std::cout << "you enter key #2" << endl; break; } case 51: {// 按下 3 temp = Scalar(50, 50, 50); add(image, temp, dst); std::cout << "you enter key #3" << endl; break; } default: break; } imshow("按键切换窗口", dst); } }
main.c
#include#include "07_opencv_mat.h" using namespace std; int main(int argc,char** argv) { //使用Mat(matrix -- 矩阵)这种类型来读取通过指定路径的图像信息并存放到变量picture中。 //图像从本质上来说都是二维的数组(矩阵) Mat picture = imread("雪地.jpeg", IMREAD_COLOR); if (picture.empty()) { cout << "could not Load image." << endl; system("pause"); return -1; } // namedWindow("输入窗口",WINDOW_FREERATIO); imshow("输入窗口", picture); QuickDemo qd; qd.keyboard_demo(picture); waitKey(0); destroyAllWindows(); system("pause"); return 0; }
运行程序,初始时,按键切换窗口与输入图像显示一样。
按下不同按键,可分别显示相应效果。



