起初,采取了简单的for循环,手动设定阈值,发现时延严重,代码如下:
vid = videoinput('winvideo',1); preview(vid); set(vid,'ReturnedColorSpace','grayscale'); while 1 pause(1);%1s figure(2); %imshow(image); [m,n] = size(image); for x = 1:m for y = 1:n if image(x,y) > 130 %手动设定阈值 image(x,y) = 0; else image(x,y) = 255; end end end figure(3); imshow(image); end
为了减小时延,采用了matlab内置函数im2bw进行二值化,并用graythresh函数自动获取阈值,设定pause延时为最小25帧(0.04秒),效果大大改善,实时性也很好,代码如下:
vid = videoinput('winvideo',1); preview(vid); set(vid,'ReturnedColorSpace','grayscale'); while 1 pause(0.04);%25帧 image = getsnapshot(vid); thresh = graythresh(image); image = im2bw(image,thresh); imshow(image); end