简体   繁体   中英

MATLAB: binary array count of groups longer than N

I have a binary array that represents object detection for individual frames of a video. I'm trying to determine from this vector how many separate events there are. I need to figure out a way to count the number of clusters of 1's in the binary array.

What's the easiest way using Matlab functions to determine how many individual groups of consecutive 1's there are that are larger than say, N=5 ?

For example for the array: 1 1 0 0 0 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 1 0 0 1 0 0 1 I would like the output to be 2 , because there are 2 groups of 1's longer than N .

I need an efficient way to do this rather than just looping through because I have to run this on about 20 thousand short videos. Kind of hoping there's a built in function for this purpose that I've missed, but any solution is welcome.

The ugly version of this code that I'm trying to speed up looks like this:

    % Count Events
    EventCount = 0;
    subcount = 0;
    N = 5;
    for e=1:length(events) % events is a binary array
        if (events(e) == 1) && (subcount == 0)
            subcount = 1;
        elseif events(e) == 1 
            subcount = subcount + 1;
        elseif (events(e) == 0) && (subcount > N)
            EventCount = EventCount + 1;
            subcount = 0;
        elseif (events(e) == 0) && (subcount <= N)
            subcount = 0;
        else
            disp('Oops, should not get here!');                  
        end
    end
    disp(EventCount);

A one linear solution:

sum(accumarray(1+cumsum([0 diff( events)==1].'),events.')>N)

Compute starting index of blocks of 1s:

idx = diff(events.')==1;

Assign a category number to each group:

catnum=1+cumsum([0 idx].');

Count number of 1s in each category

count = accumarray(catnum,events);

count how many groups of 1's are longer than N

sum(count>N)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM