Using Logical Arrays to Performing Local Math In Images?

1 view (last 30 days)
Hi all, I'm trying to write a slightly modified median filter. I have a logical array with the locations of hot pixels in an image. I'd like to replace the values of these pixels with the mean or median value of the pixels that are 2 pixels away from this central hot pixel. Example, the black pixel in the image below should be red. I'd like to take the median of the other red pixels, only and replace the black pixel with that value.
Right now I do it with a loop over x,y locations of the hot pixels, but it takes minutes, because I have about 42,000 hot pixels:
subFrame = normalizedFrames(y_hotpixels(aa)-2:2:y_hotpixels(aa)+2,x_hotpixels(aa)-2:2:x_hotpixels(aa)+2); normalizedFrames2(y_hotpixels(aa),x_hotpixels(aa)) = median(subFrame(:));
I would love to learn the MATLAB way to do this...

Answers (2)

Dmitry
Dmitry on 11 May 2016
Edited: Dmitry on 11 May 2016
I thought I figured it out, but I didn't!
Just FYI, the NON-SOLUTION I proposed is to break up this image into 4 images of just green pixels, red pixels, blue pixels, etc... median filter those images and recombine them. BUT, I don't want filter the whole image. I ONLY want to mess with the hot pixels.

Image Analyst
Image Analyst on 11 May 2016
If you want the average of the 4 pixels, that's trivial. Use conv2()
% Replace black pixels in red channel image with local mean.
% Create specialized mask
windowSize = 5; % Whatever.
middlePixel = floor(windowSize/2);
kernel = zeros(5)
kernel(1:2:end, 1:2:end) = 1
kernel(middlePixel, middlePixel) = 0; % Don't bother to include central pixel since we don't want the zero to be in the average.
% Normalize to result is the true mean, not just the sum
kernel = kernel / sum(kernel(:));
averageImage = conv2(redChannel, kernel/5^2, 'same');
mask = redChannel == 0; % Find black pixels.
% Now repair the black pixels with the average of nearby red pixels.
redChannel(mask) = averageImage(mask);
If you want the median, it's a little trickier since you can't use such a specialized mask with medfilt2(). You'll have to use nlfilter() for that. You should be able to figure it out. Let me know if you can't. I'm attaching some demos to help you.
This is for demosaicing isn't it?

Community Treasure Hunt

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

Start Hunting!