How to crop away convexity defects?

后端 未结 3 1106
半阙折子戏
半阙折子戏 2020-11-28 10:21

I\'m trying to detect and fine-locate some objects in images from contours. The contours that I get often include some noise (maybe form the background, I don\'t know). The

3条回答
  •  离开以前
    2020-11-28 10:40

    I came up with the following approach for detecting the bounds of the rectangle/square. It works based on few assumptions: shape is rectangular or square, it is centered in the image, it is not tilted.

    • divide the masked(filled) image in half along the x-axis so that you get two regions (a top half and a bottom half)
    • take the projection of each region on to the x-axis
    • take all the non-zero entries of these projections and take their medians. These medians give you the y bounds
    • similarly, divide the image in half along y-axis, take the projections on to y-axis, then calculate the medians to get the x bounds
    • use the bounds to crop the region

    Median line and the projection for a top half of a sample image is shown below.

    Resulting bounds and cropped regions for two samples:

    The code is in Octave/Matlab, and I tested this on Octave (you need the image package to run this).

    clear all
    close all
    
    im = double(imread('kTouF.png'));
    [r, c] = size(im);
    % top half
    p = sum(im(1:int32(end/2), :), 1);
    y1 = -median(p(find(p > 0))) + int32(r/2);
    % bottom half
    p = sum(im(int32(end/2):end, :), 1);
    y2 = median(p(find(p > 0))) + int32(r/2);
    % left half
    p = sum(im(:, 1:int32(end/2)), 2);
    x1 = -median(p(find(p > 0))) + int32(c/2);
    % right half
    p = sum(im(:, int32(end/2):end), 2);
    x2 = median(p(find(p > 0))) + int32(c/2);
    
    % crop the image using the bounds
    rect = [x1 y1 x2-x1 y2-y1];
    cr = imcrop(im, rect);
    im2 = zeros(size(im));
    im2(y1:y2, x1:x2) = cr;
    
    figure,
    axis equal
    subplot(1, 2, 1)
    imagesc(im)
    hold on
    plot([x1 x2 x2 x1 x1], [y1 y1 y2 y2 y1], 'g-')
    hold off
    subplot(1, 2, 2)
    imagesc(im2)
    

提交回复
热议问题