Search code examples
matlabcomputer-visionconvolutionimagefilter

Simple image filter that detects a square's upper left corner?


I'm learning computer vision and playing with filters. One question is coming up with a filter that would detect a square's upper left corner in a binary image where the square is white on black background.

In MATLAB, I try a filter that looks like this:

ul = [0 0 0; 0 1 1; 0 1 1]

But it does not seem to give me what I want. Command imshow basically displays the same image as original.

i = imread('white_square_on_black.png');
imshow(imfilter(i, ul, 'conv'));

What is the right filter to do this, and what is the principle in general?


Solution

  • First, the reason you're getting close to the same image after filtering is that your filter is detecting all pixels whose neighbors to the right and down are nonzero. This includes all of the pixels that are in the middle of the image, because they have neighbors that are nonzero.

    To fix this you need to penalize a pixel if its neighbors to the left or above are nonzero. So we can change the filter to:

    ul = [-5 -5 -5;
          -5  1  1;
          -5  1  1];
    

    That way, if even one of the undesired pixels is nonzero, it'll force the value below zero. (Assuming you're using a signed numeric type.)

    If you use this filter with your code, you'll notice that it highlights the bottom-right corner of the square. This is because conv flips the kernel before convolution. You can fix that by either changing conv to corr, or just removing it altogether, or by flipping the filter beforehand.

    I created a test image:

    enter image description here

    Then I created the filtered image using

    sf = (imfilter(img, ul) >= 3);   % make sure we get a full corner
    

    enter image description here