Contenu principal

Apply Custom Filter to Region of Interest in Image

Filtering a region of interest (ROI) is the process of applying a filter to a region in an image, where a binary mask defines the region. For example, you can apply an intensity adjustment filter to specific regions of an image. To filter an ROI in an image, use the roifilt2 function and specify the input grayscale image to be filtered, a binary mask image that defines the ROI, and a filter (either a 2-D filter or function). The roifilt2 function filters the input image and returns an image that consists of filtered values for pixels where the binary mask contains 1s and unfiltered values for pixels where the binary mask contains 0s. This type of operation is called masked filtering.

This example shows how to filter a region of interest (ROI), by using the roifilt2 function to specify the filter. The roifilt2 function enables you to specify your own function to operate on the ROI. This example uses the imadjust function to lighten parts of an image.

Read an image into the workspace and display it.

I = imread("cameraman.tif");
figure
imshow(I)

Figure contains an axes object. The hidden axes object contains an object of type image.

Create the mask image. This example uses a binary image of text as the mask image. All the 1-valued pixels define the regions of interest. The example crops the image because a mask image must be the same size as the image to be filtered.

BW = imread("text.png");
mask = BW(1:256,1:256);
figure
imshow(mask)

Figure contains an axes object. The hidden axes object contains an object of type image.

Create the function you want to use as a filter.

f = @(x) imadjust(x,[],[],0.3);

Filter the ROI, specifying the image to be filtered, the mask that defines the ROI, and the filter that you want to use.

I2 = roifilt2(I,mask,f);

Display the result.

figure
imshow(I2)

Figure contains an axes object. The hidden axes object contains an object of type image.

See Also

|