utils_.py
1    import matplotlib.pyplot as plt
2    import seaborn as sns
3    import numpy as np
4    
5    
6    def set_params():
7        sns.set_theme(style="whitegrid", rc={"axes.spines.right": False, "axes.spines.top": False})
8        plt.rcParams['figure.dpi'] = 250
9        plt.rcParams['savefig.dpi'] = 600
10   
11   def plt_img(img, title):
12       figsz = (img.shape[1] / 250, img.shape[0] / 250)
13       plt.figure(figsize=figsz)
14       _ = plt.imshow(img, cmap='gray', vmin=0, vmax=255), \
15           plt.title(title), plt.axis('off'), \
16           plt.figtext(0.5, 0.01, 'Image Size: {}'.format(img.shape),
17                       ha='center'), plt.tight_layout(), plt.show()
18   
19   def toGray(img):
20       img = np.dot(img[..., :3], [0.299, 0.587, 0.114])
21       return np.round(img).astype('uint8')
22   
23   def present(img, title, cols=1.0001):
24       plt.figure(figsize=(10, 11))
25   
26       plt.subplot(211)
27       plt.imshow(img, cmap='gray', vmin=0, vmax=255)
28       plt.axis('off')
29       plt.title(title)
30   
31       plt.subplot(212)
32       sns.histplot(img.ravel(), bins=256, lw=0, color="#05006c", binwidth=cols)
33       plt.xlim([0, 256])
34       plt.title('Histogram')
35       plt.subplots_adjust(wspace=0, hspace=0.1)
36   
37       plt.tight_layout()
38       plt.show()
39   
40   def plt_sbs(img_noisy, img_denoised, title1='Noisy Image', title2='Denoised Image'):
41       plt.figure(figsize=(10, 8))
42   
43       plt.subplot(221)
44       plt.imshow(img_noisy, cmap='gray', vmin=0, vmax=255)
45       plt.axis('off')
46       plt.title(title1)
47   
48       plt.subplot(222)
49       plt.imshow(img_denoised, cmap='gray', vmin=0, vmax=255)
50       plt.axis('off'), plt.title(title2), plt.subplot(212)
51       plt.imshow(np.hstack([img_noisy[300:400, 100:200], img_denoised[300:400, 100:200]]),
52                  cmap='gray', vmin=0, vmax=255)
53       plt.axis('off')
54       plt.title('zoomed')
55   
56       plt.subplots_adjust(wspace=0, hspace=0)
57   
58       plt.tight_layout()
59       plt.show()
60   
61   
62   def plt_modh(img_heq, modification='Equalized'):
63       image, pdf, pdf_new = img_heq
64   
65       plt.subplots(figsize=(8, 10))
66   
67       ax1 = plt.subplot(221)
68       ax1.bar(range(256), pdf, width=1.5, color='#05006c',
69               edgecolor='#05006c', linewidth=0.7)
70       ax1.set_xlim([0, 256])
71       ax1.set_title('Histogram of Original Image')
72   
73       ax2 = plt.subplot(222, sharey=ax1)
74       ax2.bar(range(256), pdf_new, width=1.5, color='#710019',
75               edgecolor='#710019', linewidth=0.7)
76       ax2.set_xlim([0, 256])
77       ax2.set_title('Histogram of {} Image'.format(modification))
78       ax2.tick_params('y', labelleft=False)
79   
80       ax3 = plt.subplot(212)
81       ax3.imshow(image, cmap='gray')
82       ax3.axis('off')
83       ax3.set_title('{} Image'.format(modification))
84   
85       plt.tight_layout()
86       plt.show()
87   
88   # Misc: functions from different Qs to be used across the project.
89   def histStretch(img, clip=0.0, lamb=255):
90       pdf = np.histogram(img.flatten(), bins=256, range=(0, 255))[0]
91   
92       ### Implementation of the `autocontrast` in Photoshop ###
93       gam = (pdf.sum()*clip/1000)
94       # Cusum Control For the Histogram Boundaries
95       cdf = pdf.cumsum()
96       cdf_r = pdf[::-1].cumsum()[::-1]
97       low = np.argmin(np.abs(cdf-gam))-1
98       high = np.argmin(np.abs(cdf_r-gam))
99       img_ = np.clip(img, low, high)
100      # This is necessary because a single 0 or 255 value would
101      # prevent the image from being stretched to that limit.
102      ###___________________________________________________###
103  
104      img_stretch = np.round(((img_-img_.min())/(img_.max()-img_.min())) * lamb)\
105          .astype(np.uint8)
106      new_pdf = np.histogram(img_stretch.flatten(), bins=256, range=(0, 255))[0]
107      return img_stretch, pdf, new_pdf
108  
109  # To create compass kernels
110  # Some parts from https://stackoverflow.com/questions/41502529/
111  def outer_slice(x):
112      return np.r_[x[0],x[1:-1,-1],x[-1,:0:-1],x[-1:0:-1,0]]
113  
114  def rotate_steps(x, shift):
115      out = np.empty_like(x)
116      N = x.shape[0]
117      idx = np.arange(x.size).reshape(x.shape)
118      for n in range((N+1)//2):
119          sliced_idx = outer_slice(idx[n:N-n,n:N-n])
120          out.ravel()[sliced_idx] = np.roll(np.take(x,sliced_idx), shift)
121      return out
122  
123  def kernel_compass(kern_N):
124      compass = [kern_N]
125      for i in range(7):
126          compass.append(rotate_steps(kern_N, i+1))
127      return compass
128  
129  def plot_compass(processed, title):
130      img_plot = np.vstack([np.hstack([processed[1], processed[2], processed[3]]),
131                            np.hstack([processed[0], np.sum(processed / 6, axis=0), processed[4]]),
132                            np.hstack([processed[7], processed[6], processed[5]])]).astype(np.uint8)
133  
134      _= plt.imshow(img_plot), plt.title(title), plt.axis('off')
135