《OpenCV2 计算机视觉编程手册》视频处理一

2024-04-07 06:38

本文主要是介绍《OpenCV2 计算机视觉编程手册》视频处理一,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

本文主要结合《OpenCV2 计算机视觉编程手册》第10章的内容,学习OpenCV 处理视频图像的一般方法,包括读入,处理,写出。

1.头文件

#ifndef HEAD_H_
#define HEAD_H_#include <iostream>
#include <iomanip>// 控制输出格式
#include <sstream>// 文件流控制
#include <string>
#include <vector>#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>#endif // HEAD_H_


2. VideoProcessor头文件


#ifndef VPROCESSOR_H_
#define VPROCESSOR_H_#include "head.h"void canny(cv::Mat& img, cv::Mat& out)
{cv::cvtColor(img, out, CV_BGR2GRAY);                      // 灰度转换cv::Canny(out, out, 100, 200);                            // Canny边缘检测cv::threshold(out, out, 128, 255, cv::THRESH_BINARY_INV); // 二值图像反转, 小于128设置为255, 否则为0;即边缘为黑色
}// 抽象类FrameProcessor中纯虚函数process必须在子类(其继承类)中重新定义。
// http://blog.csdn.net/hackbuteer1/article/details/7558868 
// 帧处理器接口
class FrameProcessor 
{public:// 处理方法,定义为纯虚函数, 让其子类实现具体的接口virtual void process(cv:: Mat &input, cv:: Mat &output)= 0;
};class VideoProcessor 
{private:cv::VideoCapture capture;           // OpenCV视频采集对象(object)void (*process)(cv::Mat&, cv::Mat&);// 每帧处理的回调函数, 函数指针调用FrameProcessor *frameProcessor;     // 基类(含纯虚函数的抽象类)FrameProcessor接口指针, 指向子类的实现bool callIt;                        // 启动回调函数与否的bool判断, true:调用, false:不调用std::string windowNameInput;        // 输入显示窗口名字std::string windowNameOutput;       // 输出显示窗口名字int delay;                          // 帧间处理延迟long fnumber;                       // 已处理帧总数long frameToStop;                   // 在该帧停止	  bool stop;                          // 停止处理标志位!std::vector<std::string> images;               // 输入的图像集或者图像向量(vector容器)std::vector<std::string>::const_iterator itImg;// 图像集的迭代器cv::VideoWriter writer;             // OpenCV视频写出对象std::string outputFile;             // 输出视频文件名字int currentIndex;                   // 输出图像集的当前索引int digits;                         // 输出图像文件名字的数字 std::string extension;              // 输出图像集的扩展名// Getting the next frame which could be: video file; camera; vector of imagesbool readNextFrame(cv::Mat& frame) {if (images.size()==0)return capture.read(frame);else {if (itImg != images.end()) {frame= cv::imread(*itImg);itImg++;return frame.data != 0;}else{return false;}}}// Writing the output frame which could be: video file or imagesvoid writeNextFrame(cv::Mat& frame) {if (extension.length()) { // 输出图像文件std::stringstream ss;ss << outputFile << std::setfill('0') << std::setw(digits) << currentIndex++ << extension;cv::imwrite(ss.str(),frame);} else { // 输出视频文件writer.write(frame);}}public:// 构造函数VideoProcessor() : callIt(false), delay(-1), fnumber(0), stop(false), digits(0), frameToStop(-1), process(0), frameProcessor(0) {}// 设置视频文件的名字bool setInput(std::string filename) {fnumber= 0;// In case a resource was already // associated with the VideoCapture instancecapture.release();            // 释放之前打开过的资源images.clear();               // 释放之前打开过的资源return capture.open(filename);// 打开视频文件}// 设置相机IDbool setInput(int id) {fnumber= 0;// In case a resource was already // associated with the VideoCapture instancecapture.release();images.clear();// 打开视频文件return capture.open(id);}// 设置输入的图像集bool setInput(const std::vector<std::string>& imgs) {fnumber= 0;// In case a resource was already // associated with the VideoCapture instancecapture.release();//释放之前打开过的资源// 输入的是图像集images= imgs;itImg= images.begin();return true;}// 设置输出视频文件, 默认参数和输入的一样bool setOutput(const std::string &filename, int codec=0, double framerate=0.0, bool isColor=true) {outputFile= filename;extension.clear();if (framerate==0.0) framerate= getFrameRate(); // 与输入相同char c[4];                     // 使用和输入相同的编码格式if (codec==0) { codec= getCodec(c);}// 打开输出视频return writer.open(outputFile, // 文件名codec,                     // 使用的解码格式 framerate,                 // 帧率getFrameSize(),            // 帧大小isColor);                  // 是否为彩色视频}// 设置输出是图像集, 后缀必须是".jpg", ".bmp" ...bool setOutput(const std::string &filename, // 文件名前缀const std::string &ext,                 // 图像文件后缀 int numberOfDigits=3,                   // 数字位数int startIndex=0)                       // 开始索引000{     if (numberOfDigits<0)                   // 数字位数必须是正数return false;outputFile = filename;                  // 文件名extension  = ext;                       // 公共后缀名digits       = numberOfDigits;          // 文件名中的数字位数 currentIndex = startIndex;              // 开始索引return true;}// 设置每一帧的回调函数void setFrameProcessor(void (*frameProcessingCallback)(cv::Mat&, cv::Mat&)) {// invalidate frame processor class instance 使FrameProcessor实例无效化frameProcessor = 0;process = frameProcessingCallback;callProcess();}// 设置FrameProcessor接口实例void setFrameProcessor(FrameProcessor* frameProcessorPtr) {// invalidate callback function 使回调函数无效化process = 0;frameProcessor= frameProcessorPtr;callProcess();}// 在frame帧停止void stopAtFrameNo(long frame) {frameToStop= frame;}// 处理回调函数void callProcess() {callIt= true;}// 不调用回调函数void dontCallProcess() {callIt= false;}// 显示输入的图像帧void displayInput(std::string wn) {windowNameInput= wn;cv::namedWindow(windowNameInput);}// 显示处理的图像帧void displayOutput(std::string wn) {windowNameOutput= wn;cv::namedWindow(windowNameOutput);}// 不显示处理的图像帧void dontDisplay() {cv::destroyWindow(windowNameInput);cv::destroyWindow(windowNameOutput);windowNameInput.clear();windowNameOutput.clear();}// 设置帧间延迟时间// 0 means wait at each frame// negative means no delayvoid setDelay(int d) {delay= d;}// 处理帧的总数long getNumberOfProcessedFrames() {return fnumber;}// 返回视频帧的大小cv::Size getFrameSize() {if (images.size()==0) {// get size of from the capture deviceint w= static_cast<int>(capture.get(CV_CAP_PROP_FRAME_WIDTH));int h= static_cast<int>(capture.get(CV_CAP_PROP_FRAME_HEIGHT));return cv::Size(w,h);} else { // if input is vector of imagescv::Mat tmp= cv::imread(images[0]);if (!tmp.data) return cv::Size(0,0);else return tmp.size();}}// 返回下一帧的帧数long getFrameNumber() {if (images.size()==0) {// get info of from the capture devicelong f= static_cast<long>(capture.get(CV_CAP_PROP_POS_FRAMES));return f; } else { // if input is vector of imagesreturn static_cast<long>(itImg-images.begin());}}// return the position in msdouble getPositionMS() {// undefined for vector of imagesif (images.size()!=0) return 0.0;double t= capture.get(CV_CAP_PROP_POS_MSEC);return t; }// 返回帧率double getFrameRate() {// undefined for vector of imagesif (images.size()!=0) return 0;double r= capture.get(CV_CAP_PROP_FPS);return r; }// 返回视频中图像的总数long getTotalFrameCount(){// for vector of imagesif (images.size()!=0) return images.size();long t= capture.get(CV_CAP_PROP_FRAME_COUNT);return t; }// 获取输入视频的编解码器int getCodec(char codec[4]) {// 未制定的图像集if (images.size()!=0) return -1;union {// 4-char编码的数据结果int value;char code[4]; } returned;// 获取编码returned.value= static_cast<int>(capture.get(CV_CAP_PROP_FOURCC));// 获得4字符codec[0]= returned.code[0];codec[1]= returned.code[1];codec[2]= returned.code[2];codec[3]= returned.code[3];// 返回对应的整数return returned.value;}// 设置帧位置bool setFrameNumber(long pos) {// for vector of imagesif (images.size()!=0) {// move to position in vectoritImg= images.begin() + pos;// is it a valid position?if (pos < images.size())return true;elsereturn false;} else { // if input is a capture devicereturn capture.set(CV_CAP_PROP_POS_FRAMES, pos);}}// go to this positionbool setPositionMS(double pos) {// not defined in vector of imagesif (images.size()!=0) return false;else return capture.set(CV_CAP_PROP_POS_MSEC, pos);}// go to this position expressed in fraction of total film lengthbool setRelativePosition(double pos) {// for vector of imagesif (images.size()!=0) {// move to position in vectorlong posI= static_cast<long>(pos*images.size()+0.5);itImg= images.begin() + posI;// is it a valid position?if (posI < images.size())return true;elsereturn false;} else { // if input is a capture devicereturn capture.set(CV_CAP_PROP_POS_AVI_RATIO, pos);}}// 停止运行void stopIt() {stop= true;}// 是否已停止运行?bool isStopped() {return stop;}// 判断是否是视频捕获设备或图像集bool isOpened() {return capture.isOpened() || !images.empty();}// 获取并处理图像void run() {cv::Mat frame;  // 当前帧cv::Mat output; // 输出帧// if no capture device has been setif (!isOpened())return;stop= false;while (!isStopped()) {// 读取下一帧if (!readNextFrame(frame))break;// 显示输出帧if (windowNameInput.length()!=0) cv::imshow(windowNameInput,frame);// 调用帧处理回调函数或FrameProcessor实例if (callIt) {  // 处理当前帧if (process)             // 如果是回调函数process(frame, output);else if (frameProcessor) //如果是FrameProcessor实例frameProcessor->process(frame,output);// 增加帧数fnumber++;}else{output= frame;}// 写出输出图像序列if (outputFile.length()!=0)writeNextFrame(output);// 显示输出帧if (windowNameOutput.length()!=0) cv::imshow(windowNameOutput,output);// 引入帧间延迟if (delay>=0 && cv::waitKey(delay)>=0)stopIt();// 检查是否需要停止运行if (frameToStop>=0 && getFrameNumber()==frameToStop)stopIt();}}
};#endif // VPROCESSOR_H_

3. 主函数


#include "head.h"
#include "videoprocessor.h"int main()
{//----Zero Test----cv::VideoCapture capture("../bike.avi"); // 打开视频/摄像头0if (!capture.isOpened())return 1;double rate= capture.get(CV_CAP_PROP_FPS);// 获取帧率bool stop(false);cv::Mat frame;                            // 当前帧cv::namedWindow("Extracted Frame");int delay= 1000/rate;                     // 延迟的毫秒//int delay = 1000;// 处理视频所有帧while (!stop) {// read next frame if anyif (!capture.read(frame))break;cv::imshow("Extracted Frame",frame);if (cv::waitKey(delay)>=0)            // 延迟等待直到cv::waitKey(delay)<0stop= true;}capture.release();                       // 因为capture自动调用析构函数,所以capture.release不是必须的!cv::waitKey();//----First Test----VideoProcessor processor;                           // 创建VideoProcessor类实例 processorprocessor.setInput("../bike.avi");                  // 打开视频文件bike.aviprocessor.displayInput("Input Video");              // 声明输入视频显示窗口processor.displayOutput("Output Video");            // 声明输出视频显示窗口processor.setDelay(1000./processor.getFrameRate()); // 设置播放视频为原始输入视频帧率processor.setFrameProcessor(canny);                 // 设置帧处理器的回调函数--cannyprocessor.run();                                    // 开始处理视频文件cv::waitKey();                                      // 等待按键响应//----Second test----processor.setInput("../bike.avi");                            // 重新设置打开视频cv::Size size= processor.getFrameSize();                      // 获取视频文件的基本信息std::cout << size.width << " " << size.height << std::endl;   // 视频图像的宽度(列)和高度(行)std::cout << processor.getFrameRate() << std::endl;           // 视频的帧率std::cout << processor.getTotalFrameCount() << std::endl;     // 视频总的帧数std::cout << processor.getFrameNumber() << std::endl;         // 视频帧的编号std::cout << processor.getPositionMS() << std::endl;          // 视频帧的位置(ms)processor.dontCallProcess();                                   // 不处理打开视频文件// 输出.jpg视频图像到output文件夹, 图像名字为bikeOut000.jpg~bikeOut118.jpgprocessor.setOutput("../output/bikeOut",".jpg");               processor.run(); cv::waitKey();// 输出bike.avi视频到output文件夹,编解码器为:XVID, 基于MPEG-4视频标准的开源解码库char codec[4];                                                 // 编解码器标识processor.setOutput("../output/bike.avi",processor.getCodec(codec),processor.getFrameRate());std::cout << "Codec: " << codec[0] << codec[1] << codec[2] << codec[3] << std::endl;processor.run();cv::waitKey();//----Three test----processor.setInput("../bike.avi");processor.displayInput("Input Video");              // 声明输入视频显示窗口processor.displayOutput("Output Video");            // 声明输出视频显示窗口processor.setFrameNumber(80);                       // 设置帧的位置processor.stopAtFrameNo(120);                       // 停止的帧位置processor.setDelay(1000./processor.getFrameRate());processor.run();cv::waitKey();return 0;
}

Canny边缘检测



视频写出结果(包含文件和视频)



制定开始帧和结束帧位置








这篇关于《OpenCV2 计算机视觉编程手册》视频处理一的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/881889

相关文章

Java使用Thumbnailator库实现图片处理与压缩功能

《Java使用Thumbnailator库实现图片处理与压缩功能》Thumbnailator是高性能Java图像处理库,支持缩放、旋转、水印添加、裁剪及格式转换,提供易用API和性能优化,适合Web应... 目录1. 图片处理库Thumbnailator介绍2. 基本和指定大小图片缩放功能2.1 图片缩放的

Python进行JSON和Excel文件转换处理指南

《Python进行JSON和Excel文件转换处理指南》在数据交换与系统集成中,JSON与Excel是两种极为常见的数据格式,本文将介绍如何使用Python实现将JSON转换为格式化的Excel文件,... 目录将 jsON 导入为格式化 Excel将 Excel 导出为结构化 JSON处理嵌套 JSON:

Spring Boot 中的默认异常处理机制及执行流程

《SpringBoot中的默认异常处理机制及执行流程》SpringBoot内置BasicErrorController,自动处理异常并生成HTML/JSON响应,支持自定义错误路径、配置及扩展,如... 目录Spring Boot 异常处理机制详解默认错误页面功能自动异常转换机制错误属性配置选项默认错误处理

SpringBoot 异常处理/自定义格式校验的问题实例详解

《SpringBoot异常处理/自定义格式校验的问题实例详解》文章探讨SpringBoot中自定义注解校验问题,区分参数级与类级约束触发的异常类型,建议通过@RestControllerAdvice... 目录1. 问题简要描述2. 异常触发1) 参数级别约束2) 类级别约束3. 异常处理1) 字段级别约束

Java堆转储文件之1.6G大文件处理完整指南

《Java堆转储文件之1.6G大文件处理完整指南》堆转储文件是优化、分析内存消耗的重要工具,:本文主要介绍Java堆转储文件之1.6G大文件处理的相关资料,文中通过代码介绍的非常详细,需要的朋友可... 目录前言文件为什么这么大?如何处理这个文件?分析文件内容(推荐)删除文件(如果不需要)查看错误来源如何避

使用Python构建一个高效的日志处理系统

《使用Python构建一个高效的日志处理系统》这篇文章主要为大家详细讲解了如何使用Python开发一个专业的日志分析工具,能够自动化处理、分析和可视化各类日志文件,大幅提升运维效率,需要的可以了解下... 目录环境准备工具功能概述完整代码实现代码深度解析1. 类设计与初始化2. 日志解析核心逻辑3. 文件处

Java docx4j高效处理Word文档的实战指南

《Javadocx4j高效处理Word文档的实战指南》对于需要在Java应用程序中生成、修改或处理Word文档的开发者来说,docx4j是一个强大而专业的选择,下面我们就来看看docx4j的具体使用... 目录引言一、环境准备与基础配置1.1 Maven依赖配置1.2 初始化测试类二、增强版文档操作示例2.

MyBatis-Plus通用中等、大量数据分批查询和处理方法

《MyBatis-Plus通用中等、大量数据分批查询和处理方法》文章介绍MyBatis-Plus分页查询处理,通过函数式接口与Lambda表达式实现通用逻辑,方法抽象但功能强大,建议扩展分批处理及流式... 目录函数式接口获取分页数据接口数据处理接口通用逻辑工具类使用方法简单查询自定义查询方法总结函数式接口

SpringBoot结合Docker进行容器化处理指南

《SpringBoot结合Docker进行容器化处理指南》在当今快速发展的软件工程领域,SpringBoot和Docker已经成为现代Java开发者的必备工具,本文将深入讲解如何将一个SpringBo... 目录前言一、为什么选择 Spring Bootjavascript + docker1. 快速部署与

Python使用vllm处理多模态数据的预处理技巧

《Python使用vllm处理多模态数据的预处理技巧》本文深入探讨了在Python环境下使用vLLM处理多模态数据的预处理技巧,我们将从基础概念出发,详细讲解文本、图像、音频等多模态数据的预处理方法,... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核