简体   繁体   English

MATLAB:大于N的组的二进制数组计数

[英]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. 我需要找出一种方法来计算二进制数组中1的簇数。

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 ? 用Matlab函数确定有多少个连续的1个单独的组大于说的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 . 例如,对于数组: 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我希望输出为2 ,因为有2组1比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. 我需要一种有效的方法来执行此操作,而不仅仅是循环播放,因为我必须在大约2万个短视频中运行此操作。 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: 计算1s块的起始索引:

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

Assign a category number to each group: 为每个组分配一个类别号:

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

Count number of 1s in each category 计算每个类别中的1

count = accumarray(catnum,events);

count how many groups of 1's are longer than N 计算多少个1的组长于N

sum(count>N)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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