As part of a larger image processing pipeline I have lots of RGB images where local regions should be smoothed with medfilt2. The regions are given by non-zero pixels of a gray mask with the same size and are less than 10% of the whole image area. Instead of smoothing the whole images by applying medfilt2 to each channel which is very time consuming I first extracted the regions with
outimage2 = uint8(zeros(h, w, 3));
[r,c] = find(outmask);
for i = 1:length(r); outimage2(r(i),c(i)) = outimage(r(i),c(i)); end;
and then apply medfilt2 to the channels of outimage2. This is 2-3 times faster than applying medfilt2 to the whole outimage because averaging over outimage2 with its many zeros seems faster than averaging over arbitrary numbers. But it could be much faster if medfilt2 could be restricted to the regions without doing anything on the rest of the image. I have tried to generalize the solution from image-processing-algorithms-on-the-roi with
outimage21 = outimage(:,:,1);
outimage21 = medfilt2(outimage21(outmask > 0), [medfilt_val(1) medfilt_val(2)]);
for the first channel but I get an "Index exceeds matrix dimensions"-error.