How can I get the histeq function to ignore NaN values?

Illustration
Anaisha - 2020-07-15T14:50:51+00:00
Question: How can I get the histeq function to ignore NaN values?

I have a set of 2D pictures, I want to only focus on a small blob in the middle while ignoring a sea of NaNs around it If I keep the NaNs, histeq spits out a plain white image. Is there a way to stop NaNs from corrupting the histeq function?

Expert Answer

Profile picture of Prashant Kumar Prashant Kumar answered . 2025-11-20

It appears that MATLAB warns you about using histeq on a matrix with NaNs and replaces them to 0.
I would suggest the following if you want to apply histeq only to non-NaN values in a matrix
 
% Setting up a sample image 
% Use im2double as double saves NaN while uint8 converts it to 0

I = im2double(imread('cameraman.tif'));

I(1:100,1:100) = NaN
I(1:256,1:100) = NaN
I(1:256,180:end) = NaN
I(1:100,:) = NaN
I(160:end,:) = NaN

figure, imshow(I)
% Duplicate Matrix
I2 = I;

% Store the output of the contrasted stretched image in I2
I2(~isnan(I2)) = histeq(I2(~isnan(I2)));
figure, imshow(I2)


J = histeq(I) transforms the grayscale image I so that the histogram of the output grayscale image J has 64 bins and is approximately flat.


Not satisfied with the answer ?? ASK NOW

Get a Free Consultation or a Sample Assignment Review!