处理视频帧

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <cv.h>
#include <iostream>
using namespace std;
using namespace cv;

void canny(cv::Mat& img,cv::Mat& out)
{
	if(3==img.channels())
		cv::cvtColor(img,out,CV_BGR2GRAY);
	cv::Canny(out,out,100,200);
	cv::threshold(out,out,128,255,cv::THRESH_BINARY_INV);
}


class VideoProcessor {

public:
	VideoProcessor():callIt(true),delay(0),
		fnumber(0),stop(false),frameToStop(-1){}

	void setFrameProcessor(
		void (*frameProcessingCallback)(cv::Mat&,cv::Mat&)){
			process = frameProcessingCallback;
	}

	bool setInput(string filename){
		fnumber = 0;
		capture.release();
		return capture.open(filename);
	}

	void displayInput(string wn){
		windowNameInput = wn;
		namedWindow(windowNameInput);
	}

	void dispalyOutput(string wn){
		windowNameOutput = wn;
		namedWindow(windowNameOutput);
	}

	void dontDisplay(){
		destroyWindow(windowNameInput);
		destroyWindow(windowNameInput);
	}

	void stopIt(){
		stop = true;
	}

	bool isStopped(){
		return stop;
	}

	bool isOpened(){
		return capture.isOpened();
	}

	void setDelay(int d){
		delay = d;
	}

	bool readNextFrame(Mat& frame){
		return capture.read(frame);
	}

	long setFrameNumber(){
		long fnumber = static_cast<long>(capture.get(CV_CAP_PROP_POS_FRAMES));
		return fnumber;
	}

	void stopAtFrameNo(long frame){
		frameToStop=frame;
	}

	double getFrameRate(){
		return capture.get(CV_CAP_PROP_FPS);
	}


	void run(){
		Mat frame;
		Mat output;
		if(!isOpened())
			return;
		stop = false;

		while(!isStopped()){
			if(!readNextFrame(frame))
				break;
			if(windowNameInput.length()!=0)
				imshow(windowNameInput,frame);
			if(callIt){
				process(frame,output);
				fnumber++;
			}else{
				output = frame;}


			if(windowNameOutput.length()!=0)
				imshow(windowNameOutput,output);

			if(delay>=0 && waitKey(delay)>0)
				stopIt();
			if(frameToStop>=0 && setFrameNumber()==frameToStop)
				stopIt();
		}
	}



private:
	VideoCapture capture;
	void (*process)(Mat&,Mat&);
	bool callIt;
	string windowNameInput;
	string windowNameOutput;
	int delay;
	long fnumber;
	long frameToStop;
	bool stop;
};

void main()
{
	VideoProcessor processor;
	processor.setInput("D://01.avi");
	processor.displayInput("Currnet Frame");
	processor.dispalyOutput("OutPut Frame");

	processor.setDelay(1000.0/processor.getFrameRate());
	processor.setFrameProcessor(canny);
	processor.run();
	waitKey();
}


  参考:OpenCV 2计算机视觉 编程手册

原文地址:https://www.cnblogs.com/bestheart/p/3639028.html