median filter on a region of interest

8 views (last 30 days)
David Levi
David Levi on 26 Apr 2022
Edited: DGM on 26 Apr 2022
In image processing toolbox, is there a way to apply median filter only on specific region of interest (and not on the whole image)?.
If there is, can you give me an example written in code?
Thanks you all !
  2 Comments
David Levi
David Levi on 26 Apr 2022
The roi is not a rectangular region.
Like you suggested , ignoring all pixels outside the ROI and set them to NaN might be a good idea.

Sign in to comment.

Answers (2)

Matt J
Matt J on 26 Apr 2022
Edited: Matt J on 26 Apr 2022
Apparently there's a way to interface with Python's median filter, which can ignore NaNs.
Presumably therefore, if you set all pixels outside the ROI to NaN, this would do what you want.

DGM
DGM on 26 Apr 2022
Edited: DGM on 26 Apr 2022
Just filter the whole image and then compose the two using a mask that defines the ROI.
A = imread('cameraman.tif');
% make a mask
imshow(A) % set up the axes
R = images.roi.Polygon(gca); % create ROI object
R.Position = [66 56;112 19;168 29;198 86;150 163;64 143;83 95];
mask = createMask(R); % create binary mask
% make a filtered copy
Amed = medfilt2(A,[5 5]);
% insert filtered region into original image
B = A;
B(mask) = Amed(mask);
imshow(B)
In this example, I used an ROI object to create a mask. You can use any method you want to create such a mask. The rest is just basic logical indexing.
  3 Comments
DGM
DGM on 26 Apr 2022
Actually, I didn't know this, but apparently you can manage to do this with roifilt2().
A = imread('cameraman.tif'); % same picture as before
mask = imread('mk.png'); % same mask as before
F = @(x) medfilt2(x,[5 5]);
B = roifilt2(A,mask,F);
imshow(B)
I don't know which is faster, but doing it by composition is at least more flexible.
EDIT: at least with cursory testing, using roifilt2() on such an image/mask isn't any faster than the logical composition example. Upon opening roifilt2(), it appears to be doing exactly what I described above -- filtering a circumscribed rectangular region and then doing the composition via simple logical indexing. With that in mind, there may be relative speed benefits if the ROI is much smaller than it is in these examples.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!