matlab - 如何对当前像素的 8 个相邻像素值求和。

标签 matlab image-processing computer-vision

我有一个二值图像。我想找到像素值 = 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   

最佳答案

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

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.

关于matlab - 如何对当前像素的 8 个相邻像素值求和。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19154331/

相关文章:

opencv - 进行人脸识别的最先进方法是什么?

c++ - 在 C++ 代码中调用 Matlab - 使用 engine.h 中的方法

regex - 在 MATLAB 中检查 UTF-8 字母是否为元音字母

multithreading - 是否可以在没有Mex的情况下在Matlab中并行加载数据文件以进行计算

PHP GD 创建一个 PNG 文件,当我尝试在同一文件上使用 imagefronpng() 时失败

用于目标检测的 OpenCV 图像预处理

node.js - Node ImageMagick 调整大小不保留文件名

python-3.x - 如何在图像中找到对象的方向?

.net - SSL 被 LD_LIBRARY_PATH 和 Matlab 破坏

python - 在opencv [python]中的轮廓内插值颜色