В этом примере показано, как усреднить изображения, полученные с течением времени.
Для некоторых продвинутых приложений процесс получения может потребовать, чтобы изображения обрабатывались по мере их получения, а результаты обработки записывались на диск.
В этом примере показано, как с помощью функций получения изображения Toolbox™ обратных вызовов, запуска и ведения журнала выполнить следующую задачу:
получать 5 кадров каждые 10 секунд
повторить ввод в эксплуатацию 10 раз
при получении изображений усредните полученные кадры и сохраните результаты на диск.
Экспериментальная установка состоит из песочных часов с белым песком, просачивающимся вниз с течением времени. В примере используется функция обратного вызова, найденная в
MATLABROOT\toolbox\imaq\imaqdemos\html\усреднение
, которая усредняет полученные кадры изображения с помощью функций Toolbox™ обработки изображений.
Создайте и настройте объект ввода видео для получения.
% Access a device using a 24 bit RGB format. vid = videoinput('winvideo', 1, 'RGB24_320x240'); % Assuming data logging can begin immediately upon START, % an immediate trigger is used. triggerconfig(vid, 'immediate'); % Configure the acquisition to collect 5 frames... framesPerTrigger = 5; vid.FramesPerTrigger = framesPerTrigger; % ...and repeat the trigger 9 additional times % (for a total of 10 trigger executions). nAdditionalTrigs = 9; vid.TriggerRepeat = nAdditionalTrigs;
Для управления скоростью, с которой будут регистрироваться кадры, доступны 2 опции:
сконфигурировать частоту кадров устройства
использовать TimerFcn для выполнения обратного вызова
Сначала будет показано решение, использующее частоту кадров устройства, а затем альтернативное решение, использующее обратный вызов таймера.
Использование опции частоты кадров обеспечит результаты обнаружения, которые наиболее тесно согласованы с фактической скоростью видеопотока устройства, тогда как использование подхода таймера обеспечивает результаты обнаружения независимо от скорости потоковой передачи устройства.
Частоту кадров устройства можно настроить, только если она поддерживается устройством. Поскольку это специфичное для устройства свойство, его можно найти в объекте источника видео.
% Access the video source selected for acquisition. src = getselectedsource(vid); % Notice this device provides a FrameRate property. get(src)
General Settings:
Parent = [1x1 videoinput]
Selected = on
SourceName = input1
Tag =
Type = videosource
UserData = []
Device Specific Properties:
BacklightCompensation = on
Brightness = 255
BrightnessMode = auto
Contrast = 127
Exposure = 511
ExposureMode = auto
Focus = 58
FrameRate = 15.1500
Gamma = 0
Iris = 4
Saturation = 108
Sharpness = 127
WhiteBalance = 100
WhiteBalanceMode = auto
% Using the FrameRate property, one can configure the acquisition source % to provide the toolbox 30 frames per second. fps = 30; src.FrameRate = num2str(fps); % Since the goal is to acquire 5 frames every 10 seconds, the toolbox % should not acquire any frames until the device provides the 300'th % frame: acqPeriod = 10; frameDelay = fps * acqPeriod
frameDelay = 300
% If the trigger is delayed by this value, the toolbox will not buffer % any frames until the 300'th frame is provided by the device. vid.TriggerFrameDelay = frameDelay; % To ensure the acquisition does not come close to timing out, configure % the time out value slightly above the expected acquisition duration. totalTrigs = nAdditionalTrigs + 1; acqDuration = (acqPeriod * totalTrigs) + 3
acqDuration = 103
vid.Timeout = acqDuration;
Для сохранения обработанных изображений на диск используется объект VIDEOWRITER. Каждый набор полученных кадров усредняется с помощью функций панели инструментов обработки изображений, а затем записывается на диск.
% Create an AVI file and configure it. vwObj = VideoWriter('imaverages.avi', 'Uncompressed AVI'); vwObj.FrameRate = fps; % Use the video input object's UserData to store processing information. userdata.average = {}; userdata.avi = vwObj; vid.UserData = userdata; % Configure the video input object to process every 5 acquired frames by % specifying a callback routine that is executed upon every trigger. vid.TriggerFcn = {'util_imaverage', framesPerTrigger}; % Now that the image acquisition and processing configuration is complete, % the acquisition is started. start(vid) % Wait for the acquisition to complete. This provides the acquisition % time to complete before the object is deleted. wait(vid, acqDuration); % Verify the averaged frames were saved to the AVI file. userdata = vid.UserData; vwObj = userdata.avi; framesWritten1 = vwObj.FrameCount
framesWritten1 =
10
% Display the resulting averages of the acquired frames. % Notice the change in the lower chamber of the hourglass over time. imaqmontage(userdata.average); title('Averaging Results - Frame Rate Based');

% Once the video input object is no longer needed, delete % it and clear it from the workspace. Also delete and clear the VideoWriter object. delete(vid) delete(vwObj) clear vid vwObj
Альтернативным решением для этой задачи является использование TimerFcn. TimerFcn может выполняться каждые 10 секунд, в этот момент получают и усредняют 5 кадров. Для инициирования сбора данных в соответствующий момент времени используются триггеры вручную.
Следует отметить, что этот подход не зависит от настройки частоты кадров устройства.
% Access a device and configure the acquisition. Have % the TimerFcn trigger the acquisition every 10 seconds. vid = videoinput('winvideo', 1, 'RGB24_320x240'); triggerconfig(vid, 'manual'); vid.TimerFcn = @trigger; vid.TimerPeriod = acqPeriod; % Configure the acquisition to collect 5 frames each time the % device is triggered. Repeat the trigger 9 additional times. vid.FramesPerTrigger = framesPerTrigger; vid.TriggerRepeat = nAdditionalTrigs; % Configure the processing routine and AVI file. vid.TriggerFcn = {'util_imaverage', framesPerTrigger}; vwObj2 = VideoWriter('imaverages2.avi', 'Uncompressed AVI'); vwObj2.FrameRate = fps; % Use the video input object's UserData to store processing information. userdata2.average = {}; userdata2.avi = vwObj2; vid.UserData = userdata2; % Start the acquisition. start(vid); wait(vid, acqDuration); % Verify the averaged frames were saved to the AVI file. userdata2 = vid.UserData; vwObj2 = userdata2.avi; framesWritten2 = vwObj2.FrameCount
framesWritten2 =
10
% Display the resulting averages of the acquired frames. % Notice the change in the lower chamber of the hourglass over time. imaqmontage(userdata2.average); title('Averaging Results - Timer Based');

% Once the video input object is no longer needed, delete % it and clear it from the workspace. Also delete and clear the VideoWriter object. delete(vid) delete(vwObj2) clear vid vwObj2