Reputation: 2269
I am trying to read and normalize a 3 channel image in numpy. For each channel in the image, I want to calculate mean of the pixel values which are greater than zero.
I started with:
from scipy import misc
img = misc.imread('test.png')
print(type(img) ) #<type 'numpy.ndarray'>
print(img.shape) #(512, 512, 3)
But I am not sure first 1.) how to index out positive values preserving dimension and without flattening the array. And 2.) How to take channel wise mean of the selected positive values.
My full normalization process is like:
img_mean = mean(img[img >0])#channel wise mean of positive pixels
img_std = std(img[img>0]) #channel wise std. deviation of positive pixels
img_norm = (img - img_mean)/img_std
img_norm[img_norm < -1] = 0 #setting pixel values less than 1 to 0.
Here is an example of image I am working with
Upvotes: 1
Views: 1766
Reputation: 221574
Easiest way would be to mask out all zeros as NaNs and then use np.nanmean
and np.nanstd
to essentially ignore the zeros
from the calculations, like so -
imgn = np.where(img>0,img,np.nan)
img_norm = (img - np.nanmean(imgn,axis=(0,1)))/np.nanstd(imgn,axis=(0,1))
Upvotes: 2