改进矩阵的滑动窗口求和的性能 [英] Improving performance of sliding window summation of a matrix

查看:97
本文介绍了改进矩阵的滑动窗口求和的性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是此帖子的后续问题:

This is a follow-up question to this post:

矩阵的滑动窗口求和

我有一个50x50的矩阵,我想对每10x10(或另一个设置大小的值-始终为正方形)重叠网格中的值求和,即:

I have a 50x50 matrix, and I'd like to sum up the values in every 10x10 (or another set size value - always square) overlapping grid i.e.:

为清楚起见,重叠窗口仅以对角线显示.然后我想在矩阵中定义一个特定的坐标(索引),例如m(23,3)并获取此坐标包含在其中的所有窗口的列表.

Overlapping windows are shown only in the diagonal for the sake of clarity. I'd then like to define a particular coordinate (index) in the matrix e.g. m(23,3) and get a list of all windows this coordinate is contained within.

我解决这个问题的尝试如下:

My attempt to solve this problem is as follows:

x = rand(50,50);
result = conv2(x, ones(10), 'valid'); %calculate the sum for each overlapping 10 x 10 window
tmp = zeros(50,50);
tmp(23,3) = 1; %location of a person, in this case - 23,3
result2 = conv2(tmp, ones(10), 'valid'); 
xx = find(result2); %get all non-zero values i.e. the windows the person falls into

然后我还想检测人所属于的任何窗口的总和也超过某个值的情况,例如:

I then also want to detect situations where any window the person is a part of, also has a sum above a certain value e.g.:

if sum(result(xx)>55)>0
   #do something
end

它可以工作-但是我需要将此作为函数的一部分来调用,并且它必须运行很多次.我敢肯定,这不是最有效的方法-目前正在向我的脚本添加不可接受的运行时级别.

It works - but I need to call this as part of a function, and it has to run a huge number of times. It is not the most efficient method of doing this i'm sure - and it is currently adding unacceptable levels of runtime to my script.

有人可以告诉我最有效的方法吗?也许不必明确检测出人落入的窗户,而是可以用数学方法计算出?归根结底,我想知道的是,在特定坐标处的给定人员是否是一个窗口的一部分,该窗口还包含一个大于X的值.

Can anybody show me the most efficient way of doing this? Perhaps the windows the person falls into does not have to be explicitly detected but can be calculated mathematically? At the end of the day, all I want to know is if a given person at a specific coordinate is part of a window that also contains a value above X.

推荐答案

我们从以下内容开始:

w = 10;           % size of square window
x = rand(50,50);  % original image
result = conv2(x, ones(w), 'valid');
                  % sum for each overlapping w x w window

请注意,result(1,1)包含窗口x(1:w,1:w)的总和.

Note that result(1,1) contains the sum for the window x(1:w,1:w).

给定原始图像x中的坐标p=[23,3],包含该坐标的窗口集就是result(p(1)-(0:9),p(2)-(0:9))处的窗口,但不包括越界索引.排除这些情况如下:

Given the coordinates p=[23,3] in the original image x, the set of windows that contain this coordinate are the ones at result(p(1)-(0:9),p(2)-(0:9)), but excluding the out-of-bound indices. Excluding these is as follows:

i = p(1)-(0:9);
j = p(2)-(0:9);
i(i<1 | i>size(result,1)) = [];
j(j<1 | j>size(result,2)) = [];

如果要查看这些窗口中的任何一个是否大于某个值,请执行

If you want to see if any of those windows is above a certain value, do

if any(result(i,j)>55)
   % do something
end

这篇关于改进矩阵的滑动窗口求和的性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆