%First, before running the code, you need to obtain the hardware support package in the additional resource manager of matlab
%Click to get more programs in the application, search camera, usb webcam and OS Generic Video Interface respectively,
%Find the programs in the following three pictures and download them to your usual folder of matlab
% Finally, find and click to install these three hardware support packages in the current folder of matlab
%----------------Common codes----------------------------
clear ; clc; close all;
%imaqhwinfo() can understand the properties of the camera, it returns a structure
%There is camera information DeviceInfo in the structure
%Includes the ID number DeviceID of the camera, and the video format SupportedFormats supported by the camera
cam_info = imaqhwinfo('winvideo');
cam_info.DeviceInfo.DeviceID;
cam_info.DeviceInfo.SupportedFormats ;
%Create video input object
%winvideo is the adapter name, the second parameter is DeviceID (camera ID);
%Usually the ID number of the camera that comes with the computer is 1
vid = videoinput('winvideo',1);
% set the video format
%video=videoinput('winvideo',1,'YUY2_1280x720');
%Set video color
%set(vid,'ReturnedColorSpace','grayscale'); % grayscale display video object
%set(vid,'ReturnedColorSpace','rgb'); % color display video object
%Display the created video object
preview(vid);
%The principle of saving the video is actually to connect the pictures of each moment in the camera to form a video, and then save it
%Create a video file object writerObj named film.avi through the VideoWriter() function
writerObj = VideoWriter( 'film.avi' );
%Set the frame rate of the video file (frames per second)
writerObj.FrameRate = 30;
%open opens the file for writing video data
open(writerObj);
%Set the total number of frames nframe that needs to be maintained
nframe = 120;
figure; %Create a new window to display each frame of the picture
for i = 1: nframe
%getsnapshot(vid) gets the image matrix representing the current moment of the video object vid
frame = getsnapshot(vid);
imshow(frame);
% Write the frame to the video object writerObj
writeVideo(writerObj,frame);
end
% close the file
close(writerObj);