【问题标题】:How to sum the 8-neighbor pixel values of the current pixel.如何对当前像素的 8 个相邻像素值求和。
【发布时间】:2013-10-03 17:00:36
【问题描述】:

我有一个二进制图像。我想找到像素值 = 1 并将其标记为当前像素。然后,我想对它的 8 个相邻像素值求和。如果当前像素的 8 个相邻像素值的总和 = 1,则用标记标记该当前像素。部分二值图像如下:

0 0 0 0 0
0 1 0 0 0
0 0 1 1 0
0 0 0 0 1
0 0 0 0 0

我尝试了以下 matlab 代码,但它有一些错误(在这一行 -> Sums = sum(currentPix, nOffsets);)。我该如何解决它?


Sums = 0; 
S = size(BW,1);
nOffsets = [S, S+1, 1, -S+1, -S, -S-1, -1, S-1]';  %8-neighbors offsets
BW_Out = BW;

for row=1:S    
   for col=1:S 
     if BW(row,col),
         break; 
      end 
   end 

   idx = sub2ind(size(BW),row,col);
   neighbors = bsxfun(@plus, idx, nOffsets); 
   currentPix = find(BW==1); %if found 1, define it as current pixel 

     while ~isempty(currentPix)

        % new current pixel list is  set of neighbors of current list.
        currentPix = bsxfun(@plus, currentPix, nOffsets);
        currentPix = currentPix(:);
        Sums = sum(currentPix, nOffsets); %error at this line

        if (Sums==1)   %if the sum of 8-neighbor values = 1, mark ROI
            plot(currentPix,'r*','LineWidth',1);
        end

        % Remove from the current pixel list pixels that are already
        currentPix(BW_Out(currentPix)) = [];

        % Remove duplicates from the list.
        currentPix = unique(currentPix);
    end
end   

【问题讨论】:

  • 您给了我们一个示例输入,但随后是一些复杂的代码。如果您提供示例输出,那么我们可能会为您找到更简洁的方法。正确的输出也将帮助人们调试您的代码。
  • @丹。谢谢你的帮助。这是输入图像 (imagehost.thaibuzz.com/…)。这是我想要的输出图像(imagehost.thaibuzz.com/…)。
  • @nkjt,感谢您的编辑。
  • 我实际上的意思是您在问题开始时拥有的 5x5 示例图像的示例输出(以数字表示)。即我的解决方案的输出是您正在寻找的吗?
  • @丹。我很抱歉造成误解。你下面的答案是正确的。

标签: matlab image-processing computer-vision


【解决方案1】:

我认为您实际上可以在一行中执行此操作(在定义内核之后)

I = [0 0 0 0 0
     0 1 0 0 0
     0 0 1 1 0
     0 0 0 0 1
     0 0 0 0 0];

K = [1 1 1;
     1 0 1;
     1 1 1;];

(conv2(I,K,'same')==1) & I

ans =

   0   0   0   0   0
   0   1   0   0   0
   0   0   0   0   0
   0   0   0   0   1
   0   0   0   0   0

分解:

M = conv2(I,K, 'same'); %// convolving with this specific kernel sums up the 8 neighbours excluding the central element (i.e. the 0 in the middle)

(M==1) & I %// Only take results where there was a 1 in the original image.

【讨论】:

  • conv2 不需要工具箱。
  • @Shai,我也觉得conv2更快。
猜你喜欢
  • 2019-07-24
  • 1970-01-01
  • 1970-01-01
  • 2013-08-27
  • 2020-11-08
  • 2023-03-10
  • 1970-01-01
  • 2017-11-01
  • 1970-01-01
相关资源
最近更新 更多