如何在图像中获取对象的像素位置

时间:2016-01-31 13:41:48

标签: matlab image-processing

假设我有一个如下所示的二进制图像。我想得到所有矩形形状和圆形形状的位置(X,Y坐标的像素值)。如何检测那里有多少个矩形和圆形。我想在Matlab中获得解决方案。矩形和圆形可以具有不同的尺寸。这里的小圆圈是噪音。提前谢谢。

1 个答案:

答案 0 :(得分:5)

你需要:

  1. 查找已连接的组件(bwconncomp
  2. 为每个连接的组件(regionprops
  3. 找到一些统计信息
  4. 丢弃太小的连接组件,在区域上定义阈值
  5. 查找连接的组件是矩形还是圆/椭圆。您可以使用循环,定义为4*pi*Area / (Perimeter^2)。完美圆圈的值为1,方格为0.785,依此类推。因此,您可以在圆度上定义阈值,以确定形状是否为圆/椭圆。
  6. 这里是结果,删除了较小的斑点,以及不同颜色的圆/椭圆和矩形:

    enter image description here

    代码:

    % Read image
    img = imread('path_to_image');
    
    % Convert to grayscale
    img = rgb2gray(img);
    
    % Remove JPEG artifacts
    bw = img > 20;
    
    % Prepare output image
    output = zeros(size(bw));
    
    % Compute connected components, and their statistics
    cc = bwconncomp(bw);
    props = regionprops(cc, 'Area', 'Perimeter');
    
    % Will contain x,y coordinates for rectanles and circles
    coord_rect = {};
    coord_circ = {};
    
    % Define thresholds on size and circularity
    th_size = 200;
    th_circ = 0.8;
    
    % For each connected component
    for i = 1 : cc.NumObjects
    
        % Is big enough?
        if(props(i).Area < th_size) 
            continue;
        end
    
        % Rectangle or Circle?
        circularity = 4 * pi * props(i).Area / (props(i).Perimeter ^ 2);
        [y,x] = ind2sub(cc.ImageSize, cc.PixelIdxList{i});
    
        if(circularity > th_circ)
            % Circle
            output(cc.PixelIdxList{i}) = 1;
            coord_circ{end+1} = [x, y];
        else
            % Rectangle
            output(cc.PixelIdxList{i}) = 2;
            coord_rect{end+1} = [x, y];
        end
    
    end
    
    % Show results
    imshow(bw);
    figure();
    imagesc(output);
    
相关问题