Labfans是一个针对大学生、工程师和科研工作者的技术社区。 论坛首页 | 联系我们(Contact Us)
MATLAB爱好者论坛-LabFans.com
返回   MATLAB爱好者论坛-LabFans.com > 其它 > 资料存档
资料存档 资料存档
 
 
主题工具 显示模式
旧 2019-12-14, 20:46   #1
poster
高级会员
 
注册日期: 2019-11-21
帖子: 3,006
声望力: 66
poster 正向着好的方向发展
帖子 如何在能量计算中消除for循环?

我正在制定一种从图像中提取信息的算法-这些信息大多数都是类似能量的数据。基本上,这是通过运行带有内核的图像来完成的(大小作为参数给出),并获取该内核中值的平方和。

这是在三个尺度上完成的,此时三个内核(补丁)的大小为(此时):smallestPatchSize,smallestPatchSize * 3,smallestPatchSize * 9(第二种和第三种情况下内核重叠)。这是针对多个颜色通道,渐变滤镜等(总共17个)完成的。

我的问题是是否可以对下面的代码进行矢量化处理?显然,这部分代码比其他任何代码都需要更多的时间来运行。我是Matlab的初学者,但仍然想尝试矢量化的技巧,但是这个让我很失望:)

for dim = 1:17 for i = 1:smallestPatchSize:(size(image,1) - currentPatchSize) for j = 1:smallestPatchSize:(size(image,2) - currentPatchSize) % calculate the position in the energy matrix % which has different dimensions than the input pictures iPosition = (i - 1 + smallestPatchSize) / smallestPatchSize; jPosition = (j - 1 + smallestPatchSize) / smallestPatchSize; % calculate the energy values and save them into the energy matrix energy(iPosition, jPosition, dim) = sum(sum(abs(... filters(i:i+currentPatchSize, j:j+currentPatchSize,dim)))) ^ 2; end end end 在此先感谢-这是我的第一个问题@ StackOverflow :)



回答:

您正在获取块的局部值之和。一个求和过滤器是可分离的,即,如果您想对m乘n求和,可以将其分解为首先取m乘1的求和,然后对结果取1乘n的和。 。请注意,使用完全卷积时,您会更频繁地使用总和,但它仍然比使用blkproc或更新的blockproc更快。

因此,即使是smallestPatchSize ,您也可以将内部循环编写为:

tmp = conv2(... conv2(abs(filter),ones(currentPatchSize,1),'same'),... ones(1,currentPatchSize,'same').^2; %# tmp contains the energy for a sliding window filter. energy = tmp((currentPatchSize/2+1):(currentPatchSize+1):size(image,1)-(currentPatchSize/2+1),... (currentPatchSize/2+1):(currentPatchSize+1):size(image,2)-(currentPatchSize/2+1));

更多&回答...
poster 当前离线   回复时引用此帖
 


发帖规则
不可以发表新主题
不可以发表回复
不可以上传附件
不可以编辑自己的帖子

启用 BB 代码
论坛禁用 表情符号
论坛启用 [IMG] 代码
论坛启用 HTML 代码



所有时间均为北京时间。现在的时间是 02:56


Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.