Jetson Nano 定时截取摄像头画面

该博客介绍了如何使用C++和Python两种方式来实现从摄像头实时抓取并处理视频帧。在C++版本中,通过OpenCV库捕获摄像头画面,调整尺寸,并每10帧保存一张图片。Python版本同样利用OpenCV进行实时视频读取,每隔一定帧数保存图片。此外,还提供了一个Python脚本,通过命令行参数接收输入视频文件,每隔指定帧数截取图片并保存。
摘要由CSDN通过智能技术生成

1. c++ 版本

#include <iostream>
#include <string>
#include <time.h>
#include <opencv4/opencv2/opencv.hpp>
#include <opencv4/opencv2/core.hpp>
#include <opencv4/opencv2/highgui.hpp>
#include <opencv4/opencv2/imgproc.hpp>
#include <opencv4/opencv2/objdetect.hpp>
#include <opencv4/opencv2/imgproc/types_c.h>
#include <opencv4/opencv2/videoio.hpp>
 
using namespace std;
using namespace cv;

//选择图片保存位置
string writePath = "/home/fan/Downloads/camera/6.camera_cut/picture/";

int main(int argc, char** argv)
{
      VideoCapture cap(0);                              // 捕获摄像头
      string name;                                      // 用于命名图片
      namedWindow("USB Camera", WINDOW_AUTOSIZE);        
      Mat img;
      int i = 0;           // 用于定时
      int photoname = 0;   // 用于图片命名
      while (true)
      {     
            if (!cap.read(img))              // 判断是否捕捉到画面
            {
                  std::cout<<"捕获失败"<<std::endl;
                  break;
            }
            // 调整画面宽高等
            int new_width,new_height,width,height,channel;
            width=img.cols;
            height=img.rows;
            channel=img.channels();
            new_width=800;
            if(width>800)
            {
                  new_height=int(new_width*1.0/width*height);
            }
            resize(img, img, cv::Size(new_width, new_height));
            imshow("USB Camera",img);        // 显示画面
            
            i = i + 1;
            if (i == 10)   // 计数到10,截取图片
            {
                  photoname++;
                  name = writePath + to_string(photoname)+".jpg";
                  imwrite(name, img);      // 保存图片
                  cout << name << endl;
                  cout << "保存" << name << "成功" << endl;
                  i = 0;
            }
            int keycode = cv::waitKey(30) & 0xff ; //ESC键退出
                  if (keycode == 27) break ;
      }
      cap.release();
      destroyAllWindows();
     //waitKey(0);
}

控制台编译

1. g++ -o camera camera_cut.cpp `pkg-config --cflags --libs opencv4`
2. ./camera

2. python版本

import cv2
import numpy as np

def main():
    print('开始运行')
    cap = cv2.VideoCapture(0)  # 捕获摄像头
    i = 0                      # 定时装置初始值
    photoname = 1              # 文件名序号初始值

    while True:
        i = i + 1
        reg, frame = cap.read()
        frame = cv2.flip(frame, 1)   # 图片左右调换
        cv2.imshow('window', frame)

        if i == 10:                 # 定时装置,定时截屏,可以修改。
            filename = str(photoname) + '.png'               # filename为图像名字,将photoname作为编号命名保存的截图
            cv2.imwrite('/home/fan/Downloads/camera/6.camera_cut/picture/' + '\\' + filename, frame)  # 截图,前面为图像存放位置
            print(filename + '保存成功')  # 打印保存成功
            i = 0                        # 清零

            photoname = photoname + 1
            if photoname >= 20:  # 最多截图20张 然后退出(如果调用photoname = 1 不用break为不断覆盖图片)
                # photoname = 1
                break
        if cv2.waitKey(1) & 0xff == ord('q'):
            break
    # 释放资源
    cap.release()
    cv2.destroyAllWindows()
if __name__ == '__main__':
    main()

3.

import argparse
import os
import cv2

def parse_args():
    """
    Parse input arguments
    """
    parser = argparse.ArgumentParser(description='Process pic')
    parser.add_argument('--input', help='video to process', dest='input', default=None, type=str)
    parser.add_argument('--output', help='pic to store', dest='output', default=None, type=str)
    #default为间隔多少帧截取一张图片
    parser.add_argument('--skip_frame', dest='skip_frame', help='skip number of video', default=1, type=int)
    #input为输入视频的路径 ,output为输出存放图片的路径
    args = parser.parse_args(['--input',r'/home/fan/Desktop/shipin/12.mp4','--output',r'/home/fan/Desktop/shipin'])
    return args

def process_video(i_video, o_video, num):
    cap = cv2.VideoCapture(0)
    # VideoCapture()中的参数若为0,则表示打开笔记本的内置摄像头
    # 若为视频文件路径,则表示打开视频

    num_frame = cap.get(cv2.CAP_PROP_FRAME_COUNT) # 获取视频总帧数
    # print(num_frame)

    expand_name = '.jpg'
    if not cap.isOpened():
        print("Please check the path.")

    cnt = 0 
    count = 0
    while 1:
        ret, frame = cap.read()
        # cap.read()表示按帧读取视频。ret和frame是获取cap.read()方法的两个返回值
        # 其中,ret是布尔值。如果读取正确,则返回TRUE;如果文件读取到视频最后一帧的下一帧,则返回False
        # frame就是每一帧的图像

        if not ret:
            break

        cnt += 1 # 从1开始计帧数
        gray_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        img1 = cv2.resize(gray_img, (288, 288))

        if cnt % num == 0: # num表示每隔num帧进行一次裁剪
            count += 1
            cv2.imwrite(os.path.join(o_video, str(count) + expand_name), img1)


if __name__ == '__main__':
    args = parse_args()
    if not os.path.exists(args.output):
        os.makedirs(args.output)
    print('Called with args:')
    print(args)
    process_video(args.input, args.output, args.skip_frame)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值