-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpscriptpy.py
288 lines (248 loc) · 10.3 KB
/
helpscriptpy.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
# -*- coding: utf-8 -*-
"""HelpScriptPy.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1_ZqIMIb-nZ87fAwkvPidCiefnPO1FmNN
"""
from os import listdir
from os.path import isfile, join
import numpy
import cv2
from scipy import signal
import glob
from PIL import Image
import os
import numpy as np
import tensorflow as tf
from os import listdir
from os.path import isfile, join
import matplotlib.pyplot as plt
from skimage import exposure
#Function to load data as particular type in array
def load_data_astype(mypath, type):
onlyfiles = [ f for f in listdir(mypath) if isfile(join(mypath,f)) ]
images = numpy.empty(len(onlyfiles), dtype=object)
for n in range(0, len(onlyfiles)):
images[n] = cv2.imread( join(mypath,onlyfiles[n]), type )
return images
#Function to load data in array
def load_data(mypath):
onlyfiles = [ f for f in listdir(mypath) if isfile(join(mypath,f)) ]
images = numpy.empty(len(onlyfiles), dtype=object)
for n in range(0, len(onlyfiles)):
images[n] = cv2.imread( join(mypath,onlyfiles[n]))
return images
#Function to display array of images
def displayImageArray(image, title):
for n in range(0, len(image)):
plt.imshow(cv2.cvtColor(image[n],cv2.COLOR_BGR2RGB))
plt.title(title)
plt.show()
#Function to display single image
def displayImage(image, title):
plt.imshow(cv2.cvtColor(image,cv2.COLOR_BGR2RGB))
plt.title(title)
plt.show()
#Function to display single image as Gray Scale
def displayGrayImage(image, title):
plt.imshow(cv2.cvtColor(image,cv2.COLOR_BGR2GRAY))
plt.title(title)
plt.show()
#Function to exclude particular channel from color image and display image with remaining channels
def rgbExclusion(image, type):
if 'red' in type:
red_image = image.copy()
red_image[:,:,2] = 0 #empty red channel
displayImage(red_image,"Excluding Red Channel")
if 'green' in type:
green_image = image.copy()
green_image[:,:,1] = 0 #empty green channel
displayImage(green_image,"Excluding Green Channel")
if 'blue' in type:
blue_image = image.copy()
blue_image[:,:,0] = 0 #empty blue channel
displayImage(blue_image,"Excluding Blue Channel")
#Function to plot histogram (simple or equilized depending upon which parameter is passed) and compute cdf
def plotHistogram(image, type):
hist,bins = np.histogram(image.flatten(),256,[0,256])
cdf = hist.cumsum()
cdf_normalized = cdf * hist.max()/ cdf.max()
plt.plot(cdf_normalized, color = 'b')
if (type==0):
plt.title("Histogram of Image")
if (type==1):
plt.title("Histogram Equilization of Image")
plt.hist(image.flatten(),256,[0,256], color = 'r')
plt.xlim([0,256])
plt.legend(('cdf','histogram'), loc = 'upper left')
plt.show()
#Function to apply histogram equilization on image
def histogramEquilization(image):
hist,bins = np.histogram(image.flatten(),256,[0,256])
cdf = 0
cdf = hist.cumsum()
cdf_normalized = cdf * hist.max()/ cdf.max()
cdf_m = np.ma.masked_equal(cdf,0)
cdf_m = (cdf_m - cdf_m.min())*255/(cdf_m.max()-cdf_m.min())
cdf = np.ma.filled(cdf_m,0).astype('uint8')
img2 = cdf[image]
equ = cv2.equalizeHist(image)
return equ
#Function to implement Convolution from scratch using image and kernel
def Convolve2dfromScratch(image, kernel, type):
kernel = np.flipud(np.fliplr(kernel)) # Flip the kernel
output = np.zeros_like(image) # convolution output
# Add zero padding to the input image
image_padded = np.zeros((image.shape[0] + 2, image.shape[1] + 2))
image_padded[1:-1, 1:-1] = image
# Loop over every pixel of the image and implement convolution operation (element wise multiplication and summation).
# You can use two loops. The result is stored in the variable output.
for x in range(image.shape[0]): # Loop over every pixel of the image
for y in range(image.shape[1]):
# element-wise multiplication and summation
output[x,y]=(kernel*image_padded[x:x+3,y:y+3]).sum()
return output
#Function to implement convolution using library function signal.convolve2d
def Convolve2dUsingLibrary(image, kernel, type):
image = signal.convolve2d(image,kernel, 'same')
return image
#Function to show comparison of both convolutions (manual and library)
def displayComaprisonConvolution(image):
fig, (ax1, ax2) = plt.subplots(1, 2)
fig.suptitle('Blur Image')
ax1.imshow(image[0], cmap=plt.cm.gray)
ax1.set_title('ManualConv')
ax2.imshow(image[3], cmap=plt.cm.gray)
ax2.set_title('ConvUsingLib')
fig, (ax1, ax2) = plt.subplots(1, 2)
fig.suptitle('Blurrer Image')
ax1.imshow(image[1], cmap=plt.cm.gray)
ax1.set_title('ManualConv')
ax2.imshow(image[4], cmap=plt.cm.gray)
ax2.set_title('ConvUsingLib')
fig, (ax1, ax2) = plt.subplots(1, 2)
fig.suptitle('Sharp Image')
ax1.imshow(image[2], cmap=plt.cm.gray)
ax1.set_title('ManualConv')
ax2.imshow(image[5], cmap=plt.cm.gray)
ax2.set_title('ConvUsingLib')
#Function to apply Box Filter given image and kernel size
def BoxFilter(imagebox, type):
if (type == 3):
kernel = np.ones((type,type),np.float32)/9 #blur
if (type == 9):
kernel = np.ones((type,type),np.float32)/25 #blur
image = signal.convolve2d(imagebox,kernel, 'same')
return image
#Function to apply Guassian Filter given image and sigma
def GuassianFilter(image, sigma):
image = cv2.GaussianBlur(image, (5,5),sigmaX=sigma)
return image
#Function to apply Median Filter given image
def MedianFilter(image):
image = signal.medfilt(image, (5,5))
return image
#Function to apply noise i.e. guassian and salt and pepper to image
def Noisy(noise_typ, image):
if noise_typ == "gauss":
mean = 0.0 # some constant
std = 5.0 # some constant (standard deviation)
noisy_img = image + np.random.normal(mean, std, image.shape)
noisy_img_clipped = np.clip(noisy_img, 0, 255)
return noisy_img_clipped
elif noise_typ == "s&p":
row,col = image.shape
s_vs_p = 0.5
amount = 0.004
out = np.copy(image)
# Salt mode
num_salt = np.ceil(amount * image.size * s_vs_p)
coords = [np.random.randint(0, i - 1, int(num_salt))
for i in image.shape]
out[coords] = 1
# Pepper mode
num_pepper = np.ceil(amount* image.size * (1. - s_vs_p))
coords = [np.random.randint(0, i - 1, int(num_pepper))
for i in image.shape]
out[coords] = 0
return out
#Function to draw mesh plot first order derivative in X direction with sigma as parameter
def first_dev_guassian_x(x, y, sigma):
temp = (x ** 2 + y ** 2) / (2 * sigma ** 2)
return -x * np.exp(-temp)/ (2* np.pi * sigma ** 4)
#Function to draw mesh plot first order derivative in Y direction with sigma as parameter
def first_dev_guassian_y(x, y, sigma):
temp = (x ** 2 + y ** 2) / (2 * sigma ** 2)
return -y * np.exp(-temp)/ (2* np.pi * sigma ** 4)
#Function to draw mesh plot second order derivative in X direction with sigma as parameter
def second_dev_guassian_x(x, y, sigma):
temp = (x ** 2 + y ** 2) / (2 * sigma ** 2)
temp1 = np.exp(-temp) /(2* np.pi * sigma ** 4)
return (-1 + x**2 / sigma**2)* temp1
#Function to draw mesh plot second order derivative in Y direction with sigma as parameter
def second_dev_guassian_y(x, y, sigma):
temp = (x ** 2 + y ** 2) / (2 * sigma ** 2)
temp1 = np.exp(-temp) /(2* np.pi * sigma ** 4)
return (-1 + y**2 / sigma**2)* temp1
#Function to compute 3d mesh plot for guassian filter
def guassian(x, y, sigma):
temp = (x ** 2 + y ** 2) / (2 * sigma ** 2)
return -1 * np.exp(-temp)/ (2* np.pi * sigma ** 2)
#Function to draw mesh plot second order derivative with sigma as parameter
def second_dev_guassian(x, y, sigma):
temp = (x ** 2 + y ** 2) / (2 * sigma ** 2)
temp1 = np.exp(-temp) /(2* np.pi * sigma ** 4)
return (x * y / 2 * np.pi *sigma**6)* temp1
#Function to apply and plot Sobel Operator given image and kernel size
def SobelOperator(image, index, size):
#Sobel X
img_SobelX = cv2.Sobel(image,cv2.CV_64F,1,0,ksize=size)
#Sobel Y
img_SobelY = cv2.Sobel(image,cv2.CV_64F,0,1,ksize=size)
#Gradient Magnitude
gradient_magnitude = np.sqrt((np.power(img_SobelX,2)+np.power(img_SobelY,2)))
fig, (ax0, ax1, ax2, ax3) = plt.subplots(1, 4, figsize=(15,15))
if size==3:
ax0.imshow(image, cmap=plt.cm.gray)
ax0.set_title('Original Image')
ax1.imshow(img_SobelX, cmap=plt.cm.gray)
ax1.set_title('Sobel X kernel size 3 ')
ax2.imshow(img_SobelY, cmap=plt.cm.gray)
ax2.set_title('Sobel Y kernel size 3')
ax3.imshow(gradient_magnitude, cmap=plt.cm.gray)
ax3.set_title('Gradient Magnitude kernel size 3 ')
if size==9:
ax0.imshow(image, cmap=plt.cm.gray)
ax0.set_title('Original Image')
ax1.imshow(img_SobelX, cmap=plt.cm.gray)
ax1.set_title('Sobel X kernel size 9 ')
ax2.imshow(img_SobelY, cmap=plt.cm.gray)
ax2.set_title('Sobel Y kernel size 9')
ax3.imshow(gradient_magnitude, cmap=plt.cm.gray)
ax3.set_title('Gradient Magnitude kernel size 9 ')
#Function to apply and plot Laplacian Operator given image
def Laplacian(image, index):
low_sigma = cv2.GaussianBlur(image,(3,3),1)
high_sigma = cv2.GaussianBlur(image,(5,5),8)
# Calculate the DoG by subtracting
laplacian = low_sigma - high_sigma
fig, (ax0, ax1, ax2, ax3) = plt.subplots(1, 4, figsize=(15,15))
ax0.imshow(image, cmap=plt.cm.gray)
ax0.set_title('Original Image')
ax1.imshow(high_sigma, cmap=plt.cm.gray)
ax1.set_title('Guassian with sigma 8')
ax2.imshow(low_sigma, cmap=plt.cm.gray)
ax2.set_title('Guassian with sigma 1')
ax3.imshow(laplacian, cmap=plt.cm.gray)
ax3.set_title('Laplacian Image')
return laplacian
#Function to apply and plot Canny Operator given image
def CannyEdgeDetector(image):
edges = cv2.Canny(image, 100, 200)
plt.rcParams['figure.figsize'] = (20.0, 16.0) # set default size of plots
fig = plt.figure()
fig.add_subplot(1, 3, 1)
plt.imshow(image,cmap=plt.cm.gray)
plt.title("GrayScale")
fig.add_subplot(1, 3, 2).imshow(edges,cmap=plt.cm.gray)
plt.title("Canny edge detector")