今天看到一个很有意思的程序,利用matlab调用摄像头。转载地址 http://www.tennfy.com/1016.html
输入
1
| cam_info = imaqhwinfo('winvideo'); |
得到
1
2
3
4
5
6
7
| cam_info =
AdaptorDllName: [1x74 char]
AdaptorDllVersion: '4.0 (R2010b)'
AdaptorName: 'winvideo'
DeviceIDs: {[1]} %摄像头ID号,这个我们经常需要用到
DeviceInfo: [1x1 struct] %设备信息,这里主要是摄像头的一些参数,比较重要 |
这里面我们最关心的就是摄像头所支持的视频格式。以我的usb摄像头为例,通过下面代码,得到摄像头的ID和支持的视频格式:
1
2
3
| cam_info = imaqhwinfo('winvideo');
cam_info.DeviceInfo.DeviceID
cam_info.DeviceInfo.SupportedFormats |
得到摄像头的ID为:1
对应的的五种视频格式:
‘YUY2_160x120′ ‘YUY2_176x144′ ‘YUY2_320x240′ ‘YUY2_352x288′ ‘YUY2_640x480′
视频的预览与采集
下面给出视频的预览和采集代码:
1
2
3
4
5
6
7
8
9
10
11
| % By tennfy
clear all; clc
vid = videoinput('winvideo', 1, 'YUY2_640x480');%创建ID为1的摄像头的视频对象,视频格式是 YUY2_640x480,这表示视频的分辨率为640x480。
set(vid,'ReturnedColorSpace','rgb');
vidRes=get(vid,'VideoResolution');
width=vidRes(1);
height=vidRes(2);
nBands=get(vid,'NumberOfBands');
figure('Name', 'Matlab调用摄像头 By tennfy', 'NumberTitle', 'Off', 'ToolBar', 'None', 'MenuBar', 'None');
hImage=image(zeros(vidRes(2),vidRes(1),nBands));
preview(vid,hImage); %打开视频预览窗口 |
视频的保存
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
| filename = 'film'; %保存视频的名字
nframe = 120; %视频的帧数
nrate = 30; %每秒的帧数
preview(vid);
set(1,'visible','off');
writerObj = VideoWriter( [filename '.avi'] );
writerObj.FrameRate = nrate;
open(writerObj);
figure;
for ii = 1: nframe
frame = getsnapshot(vid);
imshow(frame);
f.cdata = frame;
f.colormap = colormap([]) ;
writeVideo(writerObj,f);
end
close(writerObj);
closepreview |
小结