How to process large video in Matlab with for loop and without memory error

前端 未结 2 2052
甜味超标
甜味超标 2021-01-16 08:55

I\'m new to Matlab processing, and I would like to read and process a large video (more than 200k frames) inside a \"for loop\" (or without it). In particular, i would like

2条回答
  •  渐次进展
    2021-01-16 09:07

    % create video handle and get number of frames
    vidObj = VideoReader(video_file);
    nFrames = get(vidObj, 'NumberOfFrames');
    
    blocksize = 1000;
    BlocksIDs = 1:blocksize:nFrames;
    nBlocks = numel(BlocksIDs);
    
    frame_step = 3;
    
    % cell array with all correlations values grouped by block
    xcorrs_all_blocks = cell(1, nBlocks);
    
    for j = 1 : nBlocks
    
        % if this is the last block, process until the last frame
        if j == nBlocks
            last_frame = nFrames;
        % otherwise, read until next block
        else
            last_frame = BlocksIDs(j + 1);
        end
        % compute the frame numbers that we want to look at
        frame_indices = BlocksIDs(j) : frame_step : last_frame;
        nFrames = numel(frame_indices);
    
        first_frame = [];
        % pre-allocate array holding the in-block corr2 values.
        xcorrs_this_block = nan(1, nFrames-1);
    
        for k = 1 : nFrames
    
            % read-in raw frame from video file.
            raw_frame = read(vidObj, frame_indices(k));            
            % determine level for bw conversion - this might help.
            level = graythresh(raw_frame);
            raw_frame = im2bw(raw_frame, level);
    
            if k == 1
                % save current frame as first frame for later corr2 processing
                first_frame = raw_frame;
            else
                % calc the correlation between the first frame in the block and each successive frame
                xcorrs_this_block(k-1) = corr2(first_frame, raw_frame);
            end
    
    
        end
    
        % save all xcorr values into global cell array.
        xcorrs_all_blocks{j} = xcorrs_this_block;
    
    end
    

提交回复
热议问题