Tophat Example

From MATLAB Techniques for Image Processing by Steve Eddins.

A common problem with image data is nonuniform illumination. Here's an example.

I = imread('rice.png');
imshow(I)

Compute a "good" threshold.

T = graythresh(I)
T =

    0.5137

Apply the threshold and display the result.

bw = im2bw(I,T);
imshow(bw)

The result isn't good, and that's because the bottom of the image is distinctly darker than the top.

How can we correct this problem?

For an image consisting of objects on a background, one good method is to use morphological opening, with a structuring element that's larger than the objects.

Start by making a disk-shaped structuring element with radius 15.

se = strel('disk',15);

Compute the morphological opening.

background = imopen(I,se);
imshow(background)

Display the background approximation as a surface. Use 3-D rotation to view.

figure
surf(double(background(1:8:end,1:8:end)),'EdgeAlpha',0.25)
set(gca,'CLim',[0 255], ...
    'ZLim',[0 255], ...
    'YDir','reverse');

Now subtract the background from the original image.

I2 = I - background;
imshow(I2)

Repeat the threshold computation procedure.

bw2 = im2bw(I2,graythresh(I2));
imshow(bw2)

The resulting segmentation worked much better.

Subtracting an opening from the original image is an operation that has its own name: the "top-hat" operator. The Image Processing Toolbox has a function called imtophat that does the opening and subtraction for you:

I2 = imtophat(I,strel('disk',15));
imshow(I2)