1. 程式人生 > >《實用OpenCV》 影象和GUI視窗的基本操作(2)

《實用OpenCV》 影象和GUI視窗的基本操作(2)

GUI跟蹤條和函式回撥

      回撥函式

      回撥函式是指當事件發生時自動被呼叫的函式。可以和OpenCV裡面的很多事件相關聯,像滑鼠左右鍵的點選,滑塊的移動等等。

例4-2 顏色空間轉換

// Function to change between color and grayscale representations of an image using a GUI trackbar
// Author: Samarth Manoj Brahmbhatt, University of Pennsylvania
#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
using namespace std;
using namespace cv;
// Global variables
const int slider_max = 1;
int slider;
Mat img;
// Callback function for trackbar event
void on_trackbar(int pos, void *)
{
     Mat img_converted;
     if(pos > 0) cvtColor(img, img_converted, CV_RGB2GRAY);
     else img_converted = img;
     imshow("Trackbar app", img_converted);
}
int main()
{
    img = imread("image.jpg");
    namedWindow("Trackbar app");
    imshow("Trackbar app", img);
    slider = 0;
    createTrackbar("RGB <-> Grayscale", "Trackbar app", &slider, slider_max, on_trackbar);
    while(char(waitKey(1)) != 'q') {}
    return 0;
}



圖4-1 操作色彩空間轉換的程式