【问题标题】:How to Deal with Edge Cases: For Loops and Modulo如何处理边缘情况:For 循环和取模
【发布时间】:2018-06-28 13:02:42
【问题描述】:

我正在尝试对这样的图像应用基本图像处理: 我的 for 循环完全符合我的要求:它允许我找到强度最高的像素,并记住坐标那个像素。但是,只要遇到rows 的倍数(在本例中等于 18),代码就会中断。

例如,这个图像的长度(imagerows * columns)是 414。所以有 414/18 = 23 种程序失败的情况(即列数)。 也许有更好的方法来实现我的目标,但这是我能想到的唯一方法,即按像素强度对图像进行排序,同时还知道每个像素的坐标。很高兴接受替代代码的建议,但如果有人知道如何处理mod(x,18) = 0 的情况(即当向量的索引可被总行数整除时),那就太好了。

image = imread('test.tif');      % feed program an image
image_vector = image(:);         % vectorize image

[sortMax,sortIndex] = sort(image_vector, 'descend');   % sort vector so 
                              %that highest intensity pixels are at top
max_sort = [];
[rows,cols] = size(image);

for i=1:length(image_vector)
   x = mod(sortIndex(i,1),rows);         % retrieve original coordinates 
                                         % of pixels from matrix "image"
   y = floor(sortIndex(i,1)/rows) +1;
   if image(x,y) > 0.5 * max            % filter out background noise
      max_sort(i,:) = [x,y];
   else
      continue
   end
end

【问题讨论】:

    标签: matlab for-loop modulo


    【解决方案1】:

    您知道 MATLAB 索引从 1 开始,因为您在计算 y 时执行了 +1。但是你忘了先从索引中减去 1。这是正确的计算:

    index = sortIndex(i,1) - 1;
    x = mod(index,rows) + 1;
    y = floor(index/rows) + 1;
    

    此计算由函数ind2sub 执行,我建议您使用。

    编辑:实际上,ind2sub 相当于:

    x = rem(sortIndex(i,1) - 1, rows) + 1;
    y = (sortIndex(i,1) - x) / rows + 1;
    

    (您可以通过输入 edit ind2sub 看到这一点。remmod 对于正输入是相同的,因此 x 的计算方式相同。但是对于计算 y,它们避免了 floor,我猜猜它的效率略高。


    还要注意

    image(x,y)
    

    相同
    image(sortIndex(i,1))
    

    即可以直接使用线性索引索引到二维数组中。

    【讨论】:

    • 这很好地回答了我的问题,谢谢! (我的代表很低,所以我的投票不公开)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-25
    • 2012-05-14
    • 2016-05-16
    • 1970-01-01
    • 2015-09-13
    • 1970-01-01
    相关资源
    最近更新 更多