Article Directory
1. Toolbox preparation
You can directly search for the name and download it in matlab. You can download it for free as long as you log in to your account. You don't need an edu mailbox, but a QQ mailbox.
- USB camera toolbox: OS Generic Video Interface
- Deep Learning Toolboxs
- Pre-trained deep learning model (just follow the prompts to download when running the model)
You can run the code directly and download it according to the error message
2. Camera use
(1) Call the camera and take a picture to display
clear
close all
clc
vid = videoinput('winvideo',1);
preview(vid);
frame = getsnapshot(vid); % 拍照
figure;imshow(frame);
(2) Call the camera and set complex parameters
clc;
clear all;
close all;
vid = videoinput('winvideo', 2, 'YUY2_640x480'); % 设置摄像头尺寸
set(vid,'ReturnedColorSpace','rgb'); %
vidRes=get(vid,'VideoResolution');
width=vidRes(1);
height=vidRes(2);
nBands=get(vid,'NumberOfBands');
figure('Name', 'Matlab调用摄像头', 'NumberTitle', 'Off', 'ToolBar', 'None', 'MenuBar', 'None');
hImage=image(zeros(vidRes(2),vidRes(1),nBands));
preview(vid,hImage);
3. Lightweight code calls the pre-trained model to achieve CV tasks
(1) Image classification task
clear
close all
clc
%% 初始变量定义
vid = videoinput('winvideo', 2, 'YUY2_640x480'); % Connect to the camera
set(vid,'ReturnedColorSpace','rgb'); % 设置为RGB格式,否则会默认为BGR格式
net = alexnet; % 定义网络结构
%% 主程序
while true
im = getsnapshot(vid); % 取当前帧
image(im); % 显示照片
im = imresize(im,[227 227]); % 缩减图像尺寸至模型输入要求
label = classify(net,im); % 输入模型进行推理预测
title(char(label)); % 展示预测的label
drawnow
end
The recognition results are a bit difficult to describe. . . . Anyway, you can just use the picture to be happy.
(2) Target detection task
Do a small face recognition:
clear
close all
clc
%% 初始变量定义
vid = videoinput('winvideo', 2, 'YUY2_640x480'); % 定义摄像头参数
set(vid,'ReturnedColorSpace','rgb'); % 设置为RGB格式,否则会默认为BGR格式
faceDetector = vision.CascadeObjectDetector(); % 定义人脸识别工具
%% 主程序
while true
im = getsnapshot(vid); % 取当前帧
im = imresize(im,[227 227]); % 缩减图像尺寸
bbox = step(faceDetector, im); % 将图片输入人脸检测器,返回识别结果的bounding box信息
imgOut = insertObjectAnnotation(im,'rectangle',bbox,'Face'); % 给原图识别结果画框
imgOut = imresize(imgOut,[640 480]); % 重新放回原尺寸,便于观察效果
image(imgOut); % 显示照片
end