【C++】OpenCV4-图像、视频的读取和保存

发布时间 2024-01-07 17:19:42作者: wshidaboss

#include <iostream>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
int main() {
    //图像的读取
  Mat img = imread("C:/img/3.jpg", IMREAD_COLOR);
  Mat gray = imread("C:/img/3.jpg", IMREAD_GRAYSCALE);

  Mat a = (Mat_<int>(3, 3) << 1, 2, 3, 4, 5, 6, 7, 8, 9);
  /*namedWindow("IMG1", WINDOW_AUTOSIZE);
  namedWindow("IMG2", WINDOW_FREERATIO);
  imshow("IMG1", img);
  imshow("IMG2", gray);
  imwrite("C:/img/newgray.jpg", gray);*/
  waitKey(0);
  destroyAllWindows();
  return 0;
}

 

#include <iostream>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
int main() {
  //读取视频
  //VideoCapture video;
  //video.open("C:/opencv/sources/samples/cpp/tutorial_code/calib3d/real_time_pose_estimation/Data/box.mp4");
  //if (!video.isOpened()) {
  //  cout << "请检查文件路径!";
  //  return -1;
  //}
  //cout << "视频帧率:" << video.get(CAP_PROP_FPS) << endl;
  //cout << "视频宽度:" << video.get(CAP_PROP_FRAME_WIDTH) << endl;

  //while (1) {
  //  Mat frame;
  //  video >> frame;
  //  if (frame.empty()) {
  //    break;
  //  }
  //  imshow("img", frame);
  //  //waitKey(20);
  //  uchar c = waitKey(1000 / video.get(CAP_PROP_FPS));
  //  if (c == 'q')break;
  //}

  //开启摄像头读取视频并保存视频
  Mat img;
  VideoCapture video(0);

  if (!video.isOpened()) {
    cout << "打开摄像头失败,请确认摄像头是否安装成功";
    return -1;
  }
  video >> img;//获取图像
  if (img.empty()) {
    cout << "没有获取到图像" << endl;
    return -1;
  }
  //判断视频类是否为彩色
  bool isColor = (img.type() == CV_8UC3);

  VideoWriter writer;
  //选择编码格式
  int codec = VideoWriter::fourcc('M', 'J', 'P', 'G');

  double fps = 25.0;//设置视频帧率
  string filename = "live.avi";
  writer.open(filename, codec, fps, img.size(), isColor);

  if (!writer.isOpened()) {
    cout << "打开视频文件失败,请确认是否为合法输入" << endl;
    return -1;
  }

  while (1) {
    if (!video.read(img)) {
      cout << "摄像头断开连接或者视频读取完成" << endl;
      break;
    }
    writer.write(img);
    imshow("Live", img);
    char c = waitKey(50);
    if (c == 27) {
      break;
    }
  }

  return 0;
}