1、图片的读取、显示和保存
//图片的读取与保存
#include <stdio.h>
#include <iostream>
#include <string>
#include <opencv2\opencv.hpp>
using namespace std;
using namespace cv;
int main()
{
cv::Mat a;
a = cv::imread("picture.jpeg", IMREAD_GRAYSCALE);//以灰色图像读取
if (!a.empty())
{
cout << "图像读取成功" << endl;
}
else
return -1;
cv::namedWindow("小黄人",WINDOW_NORMAL);//WINDOW_NORMAL使窗口可以调整大小,更多可选参数查看源码
cv::imshow("小黄人", a);
if (cv::imwrite("picture_gray.png", a))
{
cout << "图像保存成功" << endl;
}
else
cout << "图像保存失败" << endl;
cv::waitKey(0);//防止图片一闪而过
return 0;
}
2、视频的读取、显示和保存
//视频的读取与显示
#include <stdio.h>
#include <iostream>
#include <string>
#include <opencv2\opencv.hpp>
using namespace std;
using namespace cv;
int main()
{
VideoCapture video("xiaohuangren.mp4");
if (!video.isOpened())
{
cout << "视频打不开" << endl;
}
else
{
cout << "视频中图像的宽度:" << video.get(CAP_PROP_FRAME_WIDTH) << endl;
cout << "视频中图像的高度:" << video.get(CAP_PROP_FRAME_HEIGHT) << endl;
cout << "视频的帧率:" << video.get(CAP_PROP_FPS) << endl;
cout << "视频的总帧数:" << video.get(CAP_PROP_FRAME_COUNT) << endl;
}
while (1)
{
Mat frame;
video >> frame;
if (frame.empty())
{
break;//所有帧图像都赋值给frame后再赋值一次frame变为空
}
cv::imshow("小黄人", frame);
waitKey(1000 / video.get(CAP_PROP_FPS));
}
waitKey(0);
return 0;
}
//调用摄像头进行拍摄显示
#include <stdio.h>
#include <iostream>
#include <string>
#include <opencv2\opencv.hpp>
using namespace std;
using namespace cv;
int main()
{
VideoCapture video(0);//0表示摄像头的ID号
if (!video.isOpened())
{
cout << "视频打不开" << endl;
}
else
{
cout << "视频中图像的宽度:" << video.get(CAP_PROP_FRAME_WIDTH) << endl;
cout << "视频中图像的高度:" << video.get(CAP_PROP_FRAME_HEIGHT) << endl;
cout << "视频的帧率:" << video.get(CAP_PROP_FPS) << endl;
cout << "视频的总帧数:" << video.get(CAP_PROP_FRAME_COUNT) << endl;
}
while (1)
{
Mat frame;
video >> frame;
cv::imshow("你", frame);
waitKey(10);
}
waitKey(0);
return 0;
}
//调用摄像头进行拍摄并保存视频
#include <stdio.h>
#include <iostream>
#include <string>
#include <opencv2\opencv.hpp>
using namespace std;
using namespace cv;
int main()
{
Mat img;
VideoCapture video(0);
if (video.isOpened())
{
cout << "摄像头打开成功" << endl;
}
else
{
cout << "摄像头打开失败" << endl;
return -1;
}
video >> img;
if (img.empty())
{
cout << "图片拍摄失败" << endl;
}
bool is_color = (img.type() == CV_8UC3);//判断图片是否为彩色图像
VideoWriter writer;
int video_encode = VideoWriter::fourcc('D','I','V','X');
writer.open("video_camera.mp4", video_encode, 30, img.size(), is_color);//30表示帧率
while (1)
{
if (!(video.read(img)))
{
cout << "摄像头读取完毕或者摄像头断开连接" << endl;
break;
}
writer.write(img);
imshow("video", img);
char c = waitKey(50);
if (c == 27)
{
break;
}
}
return 0;
}