Усреднение изображений в зависимости от времени

В этом примере показано, как насчитать изображения, получаемые в зависимости от времени.

Для некоторых усовершенствованных приложений процесс приобретения может потребовать, чтобы изображения были обработаны, когда они получены, в то время как ваши результаты обработки зарегистрированы к диску.

Используя коллбэки Image Acquisition Toolbox™, инициирование и логгирование функций, этот пример иллюстрирует, как выполнить следующую задачу:

  • получайте 5 систем координат каждые 10 секунд

  • повторите приобретение 10 раз

  • при получении изображений насчитайте полученные системы координат и сохраните результаты на диск.

Экспериментальная настройка состоит из песочных часов с белым песком, сочащимся вниз в зависимости от времени. Пример использует функцию обратного вызова, найденную в

  • MATLABROOT\toolbox\imaq\imaqdemos\html\averaging

директория, что средние значения получили фреймы изображения с помощью функций Image Processing 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, чтобы выполнить коллбэк

Во-первых, решение с помощью частоты кадров устройства будет показывать, сопровождать альтернативное решение с помощью коллбэка таймера.

Используя частоту кадров опция обеспечит результаты приобретения, которые наиболее тесно выравниваются с фактическим уровнем видеопотока устройства, тогда как использование подхода таймера обеспечивает результаты приобретения, независимые от уровня потоковой передачи устройства.

Основанное на частоте кадров приобретение (решение 1)

Частота кадров устройства может только быть сконфигурирована, если она поддерживается устройством. Когда это - устройство определенное свойство, это может быть найдено на объекте источника видеосигнала.

% 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 используется. Каждый набор полученных систем координат усреднен с помощью функций Image Processing Toolbox, и затем записан в диск.

% 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

Основанное на таймере приобретение (решение 2)

Альтернативное решение для этой задачи состоит в том, чтобы использовать 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

Для просмотра документации необходимо авторизоваться на сайте