|
a |
|
b/utils/equalizer.py |
|
|
1 |
import numpy as np |
|
|
2 |
import pickle |
|
|
3 |
|
|
|
4 |
class histEq: |
|
|
5 |
def __init__(self,X_sample,levels=10000,nbins=10000, path=[]): #X_sample is a list of one or more images sampled from the distribution, levels is the ourput norm range |
|
|
6 |
if len(path) > 0: |
|
|
7 |
self.load(path) |
|
|
8 |
else: |
|
|
9 |
self.nbins = nbins |
|
|
10 |
self.init(X_sample,levels,nbins) |
|
|
11 |
|
|
|
12 |
def init(self,X_sample,levels,nbins): |
|
|
13 |
#format X |
|
|
14 |
X_f = np.concatenate(X_sample) |
|
|
15 |
self.N = np.prod(X_f.shape) #number of pixels |
|
|
16 |
self.L = levels #grey levels to eq to |
|
|
17 |
|
|
|
18 |
hist, bins = np.histogram(X_f.ravel(), nbins) |
|
|
19 |
self.hist = hist/len(X_sample) #normalize to thenumber of images |
|
|
20 |
self.bins = bins + ((max(bins)-min(bins))/len(bins))/2 #center of each bin |
|
|
21 |
self.bins = self.bins[:nbins] |
|
|
22 |
self.cdf = np.cumsum(self.hist) |
|
|
23 |
self.cdf_min = np.min(self.cdf) |
|
|
24 |
|
|
|
25 |
def equalize(self,image): |
|
|
26 |
out = np.interp(image.flat, self.bins, self.cdf) |
|
|
27 |
return out.reshape(image.shape) |
|
|
28 |
|
|
|
29 |
def dequalize(self,image): |
|
|
30 |
out = np.interp(image.flat, self.cdf, self.bins) |
|
|
31 |
return out.reshape(image.shape) |
|
|
32 |
|
|
|
33 |
def save(self,path=None): |
|
|
34 |
if path is None: |
|
|
35 |
return [self.bins,self.cdf] |
|
|
36 |
with open(path, 'wb') as f: |
|
|
37 |
pickle.dump([self.bins,self.cdf], f) |
|
|
38 |
|
|
|
39 |
def load(self,path): |
|
|
40 |
with open(path, 'rb') as f: |
|
|
41 |
data = pickle.load(f) |
|
|
42 |
self.bins = data[0] |
|
|
43 |
self.cdf = data[1] |
|
|
44 |
|