├── Python#002 video2image.py ├── Python#003 Part 1 background_image.py ├── Python#003 Part 1 background_image_100images.py ├── Python#003 Part 2 segmented_image.py ├── Python#003 Part 2 segmented_video.py ├── Python#004 histogram_equalization.py ├── Python#005 Image Blur and Sharpen.py ├── Python#006 Ideal Low and High Pass Filter.py ├── Python#007 Frequency Domain Filter Gaussian Filter.py ├── Python#008 Butterworth Filter.py ├── Python#009 Frequency domain filter Laplacian Filter.py ├── Python#010 Spatial Domain Image Filter using Laplacian Filter.py ├── Python#011 Unsharp Masking and High-boost in spatial domain.py ├── Python#012 Unsharp Masking and Highboost Filtering in Frequency Domain.py ├── Python#013 Edge Detection using Sobel Operator.py ├── Python#014 Add a Gaussian Noise to an Image.py ├── Python#015 How to add an uniform noise to image.py ├── Python#016 Manually Add a Salt and Paper Noise.py ├── Python#017 Denoising an Image using Mean and Median Filter.py ├── Python#018 Create a Motion Blur Image.py ├── Python#019 Interactive Widget.ipynb ├── Python#020 Manually Convert Color Image into Grayscale Image .ipynb ├── Python#021 Image Denoising using PCA.ipynb ├── Python#022 Affine Transformation.ipynb ├── Python#023 Histogram Matching.ipynb ├── Python#024 - Image Restoration using Wiener restoration.ipynb ├── Python#025 - Image IO in Python.ipynb └── README.md /Python#002 video2image.py: -------------------------------------------------------------------------------- 1 | # Extract image from video file 2 | 3 | import cv2 4 | 5 | video = cv2.VideoCapture('problem_1_surveillance.mp4') 6 | 7 | i = 1 8 | while True: 9 | ret, image = video.read() 10 | 11 | if ret == False: 12 | break 13 | 14 | cv2.imwrite('Frames/image' + str(i) +'.jpg', image) 15 | 16 | i += 1 17 | 18 | video.release() 19 | -------------------------------------------------------------------------------- /Python#003 Part 1 background_image.py: -------------------------------------------------------------------------------- 1 | # import the library 2 | import cv2 3 | import numpy as np 4 | from matplotlib import pyplot as plt 5 | 6 | # read a video file and create a matrix A 7 | video = cv2.VideoCapture('problem_1_surveillance.mp4') 8 | 9 | matrixA = [] 10 | 11 | while True: 12 | ret, image = video.read() # read each image from video 13 | if ret == False: # break the while loop 14 | break 15 | image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # convert to grayscale 16 | matrixA.append(image) # append to matrixA 17 | 18 | matrixA = np.array(matrixA) # convert to numpy array 19 | 20 | video.release() 21 | 22 | # display image at time t 23 | t = 10 24 | plt.imshow(matrixA[t,:,:], cmap='gray') 25 | plt.axis('off') 26 | plt.show() 27 | 28 | # create the background image b 29 | b = np.median(matrixA,axis=0) # calculate the median 30 | b = b.astype(np.uint8) # change the data type 31 | 32 | # showing the result 33 | plt.imshow(b, cmap='gray') 34 | plt.axis('off') 35 | plt.show() 36 | -------------------------------------------------------------------------------- /Python#003 Part 1 background_image_100images.py: -------------------------------------------------------------------------------- 1 | # import the library 2 | import cv2 3 | import numpy as np 4 | from matplotlib import pyplot as plt 5 | 6 | # read a video file and create a matrix A 7 | video = cv2.VideoCapture('problem_1_surveillance.mp4') 8 | 9 | matrixA = [] 10 | 11 | for i in range(100): 12 | ret, image = video.read() # read each image from video 13 | image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # convert to grayscale 14 | matrixA.append(image) # append the image into matrix A 15 | 16 | matrixA = np.array(matrixA) # convert to numpy array 17 | 18 | video.release() # release the video object 19 | 20 | # display image at time t 21 | t = 50 22 | plt.imshow(matrixA[t,:,:], cmap='gray') 23 | plt.axis('off') 24 | plt.show() 25 | 26 | # create the background image b 27 | b = np.median(matrixA,axis=0) 28 | b = b.astype(np.uint8) 29 | 30 | # showing the result 31 | plt.imshow(b, cmap='gray') 32 | plt.axis('off') 33 | plt.show() 34 | -------------------------------------------------------------------------------- /Python#003 Part 2 segmented_image.py: -------------------------------------------------------------------------------- 1 | # import the library 2 | import cv2 3 | import numpy as np 4 | from matplotlib import pyplot as plt 5 | 6 | # read a video file and create a matrix A 7 | video = cv2.VideoCapture('problem_1_surveillance.mp4') 8 | 9 | matrixA = [] 10 | 11 | while True: 12 | ret, image = video.read() # read each image from video 13 | if ret == False: # break the while loop 14 | break 15 | image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # convert to grayscale 16 | matrixA.append(image) # append to matrixA 17 | 18 | matrixA = np.array(matrixA) # convert to numpy array 19 | 20 | video.release() 21 | 22 | # create the background image b 23 | b = np.median(matrixA,axis=0) # calculate the median 24 | b = b.astype(np.uint8) # change the data type 25 | 26 | plt.imshow(b, cmap='gray') 27 | plt.axis('off') 28 | plt.show() 29 | 30 | # select any image 31 | t = 0 32 | 33 | plt.imshow(matrixA[t,:,:], cmap='gray') 34 | plt.axis('off') 35 | plt.show() 36 | 37 | # image subtraction (absolute) 38 | g = cv2.absdiff(matrixA[t,:,:], b) 39 | 40 | plt.imshow(g, cmap='gray') 41 | plt.axis('off') 42 | plt.show() 43 | 44 | # image thresholding 45 | _, gT = cv2.threshold(g, 25, 255, cv2.THRESH_BINARY) 46 | 47 | plt.imshow(gT, cmap='gray') 48 | plt.axis('off') 49 | plt.show() 50 | -------------------------------------------------------------------------------- /Python#003 Part 2 segmented_video.py: -------------------------------------------------------------------------------- 1 | # import the library 2 | import cv2 3 | import numpy as np 4 | from matplotlib import pyplot as plt 5 | 6 | # read a video file and create a matrix A 7 | video = cv2.VideoCapture('problem_1_surveillance.mp4') 8 | 9 | matrixA = [] 10 | 11 | while True: 12 | ret, image = video.read() # read each image from video 13 | if ret == False: # break the while loop 14 | break 15 | image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # convert to grayscale 16 | matrixA.append(image) # append to matrixA 17 | 18 | matrixA = np.array(matrixA) # convert to numpy array 19 | 20 | video.release() 21 | 22 | # create the background image b 23 | b = np.median(matrixA,axis=0) # calculate the median 24 | b = b.astype(np.uint8) # change the data type 25 | 26 | # video segmentation 27 | video = cv2.VideoCapture('problem_1_surveillance.mp4') 28 | while True: 29 | ret, image = video.read() 30 | if ret == False: 31 | break 32 | image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) 33 | 34 | g = cv2.absdiff(image, b) # image differece 35 | _, gT = cv2.threshold(g, 25, 255, cv2.THRESH_BINARY) # image thresholding 36 | cv2.imshow('Image Subtraction', gT) 37 | if cv2.waitKey(30) & 0xFFF == 27: 38 | break 39 | 40 | video.release() 41 | cv2.destroyAllWindows() 42 | -------------------------------------------------------------------------------- /Python#004 histogram_equalization.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | from matplotlib import pyplot as plt 4 | 5 | # original image 6 | f = cv2.imread('original image.png', 0) 7 | 8 | plt.imshow(f, cmap='gray') 9 | plt.axis('off') 10 | plt.show() 11 | 12 | hist, bins = np.histogram(f.flatten(), 13 | bins=256, 14 | range=[0,256]) 15 | cdf = hist.cumsum() 16 | cdf_normalized = cdf / cdf.max() 17 | 18 | fig, ax = plt.subplots(figsize=(5,5)) 19 | 20 | ax.hist(f.flatten(), 21 | bins=256, 22 | range=[0,256], 23 | color='r') 24 | ax.set_xlabel('pixel intensity') 25 | ax.set_ylabel('#pixels') 26 | ax.set_xlim(0,255) 27 | 28 | ax2 = ax.twinx() 29 | ax2.plot(cdf_normalized, color='b') 30 | ax2.set_ylabel('cdf') 31 | ax2.set_ylim(0,1) 32 | 33 | plt.show() 34 | 35 | # histogram equalization (global) 36 | equ = cv2.equalizeHist(f) 37 | 38 | plt.imshow(equ, cmap='gray') 39 | plt.axis('off') 40 | plt.show() 41 | 42 | hist, bins = np.histogram(equ.flatten(), 43 | bins=256, 44 | range=[0,256]) 45 | cdf = hist.cumsum() 46 | cdf_normalized = cdf / cdf.max() 47 | 48 | fig, ax = plt.subplots(figsize=(5,5)) 49 | 50 | ax.hist(equ.flatten(), 51 | bins=256, 52 | range=[0,256], 53 | color='r') 54 | ax.set_xlabel('pixel intensity') 55 | ax.set_ylabel('#pixels') 56 | ax.set_xlim(0,255) 57 | 58 | ax2 = ax.twinx() 59 | ax2.plot(cdf_normalized, color='b') 60 | ax2.set_ylabel('cdf') 61 | ax2.set_ylim(0,1) 62 | 63 | plt.show() 64 | 65 | # CLAHE (local) 66 | clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8)) 67 | clahef = clahe.apply(f) 68 | 69 | plt.imshow(clahef, cmap='gray') 70 | plt.axis('off') 71 | plt.show() 72 | 73 | hist, bins = np.histogram(clahef.flatten(), 74 | bins=256, 75 | range=[0,256]) 76 | cdf = hist.cumsum() 77 | cdf_normalized = cdf / cdf.max() 78 | 79 | fig, ax = plt.subplots(figsize=(5,5)) 80 | 81 | ax.hist(clahef.flatten(), 82 | bins=256, 83 | range=[0,256], 84 | color='r') 85 | ax.set_xlabel('pixel intensity') 86 | ax.set_ylabel('#pixels') 87 | ax.set_xlim(0,255) 88 | ax.set_ylim(0,60000) 89 | 90 | ax2 = ax.twinx() 91 | ax2.plot(cdf_normalized, color='b') 92 | ax2.set_ylabel('cdf') 93 | ax2.set_ylim(0,1) 94 | 95 | plt.show() 96 | -------------------------------------------------------------------------------- /Python#005 Image Blur and Sharpen.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | import matplotlib.pyplot as plt 4 | 5 | # original image 6 | original_image = cv2.imread('image.png', 0) 7 | 8 | # blur and sharpen convolution kernel 9 | M = 3 10 | blur_kernel = np.ones((M,M)) * 1/(M*M) 11 | 12 | sharpen_kernel = np.array([[0, -1, 0], 13 | [-1, 5, -1], 14 | [0, -1, 0]], 15 | dtype=np.float32) 16 | 17 | # apply the covolution 18 | blur_image = cv2.filter2D(src=original_image, 19 | ddepth=-1, 20 | kernel=blur_kernel) 21 | 22 | sharpen_image = cv2.filter2D(src=original_image, 23 | ddepth=-1, 24 | kernel=sharpen_kernel) 25 | 26 | # display the result 27 | plt.imshow(original_image, cmap='gray') 28 | plt.axis('off') 29 | plt.show() 30 | 31 | plt.imshow(blur_image, cmap='gray') 32 | plt.axis('off') 33 | plt.show() 34 | 35 | plt.imshow(sharpen_image, cmap='gray') 36 | plt.axis('off') 37 | plt.show() 38 | 39 | # built in image bluring 40 | builtin_blur = cv2.blur(src=original_image, ksize=(3,3)) 41 | 42 | plt.imshow(builtin_blur, cmap='gray') 43 | plt.axis('off') 44 | plt.show() 45 | 46 | builtin_median = cv2.medianBlur(src=original_image, ksize=3) 47 | 48 | plt.imshow(builtin_median, cmap='gray') 49 | plt.axis('off') 50 | plt.show() 51 | 52 | builtin_gaussian = cv2.GaussianBlur(src=original_image, 53 | ksize=(3,3), 54 | sigmaX=0, 55 | sigmaY=0) 56 | 57 | plt.imshow(builtin_gaussian, cmap='gray') 58 | plt.axis('off') 59 | plt.show() 60 | -------------------------------------------------------------------------------- /Python#006 Ideal Low and High Pass Filter.py: -------------------------------------------------------------------------------- 1 | # libraries 2 | import cv2 3 | import numpy as np 4 | import matplotlib.pyplot as plt 5 | 6 | # original image 7 | f = cv2.imread('rubik.jpg',0) 8 | 9 | plt.imshow(f, cmap='gray') 10 | plt.axis('off') 11 | plt.show() 12 | 13 | # image in frequency domain 14 | F = np.fft.fft2(f) 15 | plt.imshow(np.log1p(np.abs(F)), 16 | cmap='gray') 17 | plt.axis('off') 18 | plt.show() 19 | 20 | Fshift = np.fft.fftshift(F) 21 | plt.imshow(np.log1p(np.abs(Fshift)), 22 | cmap='gray') 23 | plt.axis('off') 24 | plt.show() 25 | 26 | # Filter: Low pass filter 27 | M,N = f.shape 28 | H = np.zeros((M,N), dtype=np.float32) 29 | D0 = 50 30 | for u in range(M): 31 | for v in range(N): 32 | D = np.sqrt((u-M/2)**2 + (v-N/2)**2) 33 | if D <= D0: 34 | H[u,v] = 1 35 | else: 36 | H[u,v] = 0 37 | 38 | plt.imshow(H, cmap='gray') 39 | plt.axis('off') 40 | plt.show() 41 | 42 | # Ideal Low Pass Filtering 43 | Gshift = Fshift * H 44 | plt.imshow(np.log1p(np.abs(Gshift)), 45 | cmap='gray') 46 | plt.axis('off') 47 | plt.show() 48 | 49 | # Inverse Fourier Transform 50 | G = np.fft.ifftshift(Gshift) 51 | plt.imshow(np.log1p(np.abs(G)), 52 | cmap='gray') 53 | plt.axis('off') 54 | plt.show() 55 | 56 | g = np.abs(np.fft.ifft2(G)) 57 | plt.imshow(g, cmap='gray') 58 | plt.axis('off') 59 | plt.show() 60 | 61 | 62 | # Filter: High pass filter 63 | H = 1 - H 64 | 65 | plt.imshow(H, cmap='gray') 66 | plt.axis('off') 67 | plt.show() 68 | 69 | # Ideal High Pass Filtering 70 | Gshift = Fshift * H 71 | plt.imshow(np.log1p(np.abs(Gshift)), 72 | cmap='gray') 73 | plt.axis('off') 74 | plt.show() 75 | 76 | # Inverse Fourier Transform 77 | G = np.fft.ifftshift(Gshift) 78 | plt.imshow(np.log1p(np.abs(G)), 79 | cmap='gray') 80 | plt.axis('off') 81 | plt.show() 82 | 83 | g = np.abs(np.fft.ifft2(G)) 84 | plt.imshow(g, cmap='gray') 85 | plt.axis('off') 86 | plt.show() 87 | -------------------------------------------------------------------------------- /Python#007 Frequency Domain Filter Gaussian Filter.py: -------------------------------------------------------------------------------- 1 | # libraries 2 | import cv2 3 | import numpy as np 4 | import matplotlib.pyplot as plt 5 | 6 | # open the image f 7 | f = cv2.imread('rubik.jpg',0) 8 | 9 | plt.figure(figsize=(5,5)) 10 | plt.imshow(f, cmap='gray') 11 | plt.axis('off') 12 | plt.show() 13 | 14 | # transform the image into frequency domain, f --> F 15 | F = np.fft.fft2(f) 16 | Fshift = np.fft.fftshift(F) 17 | 18 | plt.figure(figsize=(5,5)) 19 | plt.imshow(np.log1p(np.abs(F)), cmap='gray') 20 | plt.axis('off') 21 | plt.show() 22 | 23 | plt.figure(figsize=(5,5)) 24 | plt.imshow(np.log1p(np.abs(Fshift)), cmap='gray') 25 | plt.axis('off') 26 | plt.show() 27 | 28 | # Create Gaussin Filter: Low Pass Filter 29 | M,N = f.shape 30 | H = np.zeros((M,N), dtype=np.float32) 31 | D0 = 10 32 | for u in range(M): 33 | for v in range(N): 34 | D = np.sqrt((u-M/2)**2 + (v-N/2)**2) 35 | H[u,v] = np.exp(-D**2/(2*D0*D0)) 36 | 37 | plt.figure(figsize=(5,5)) 38 | plt.imshow(H, cmap='gray') 39 | plt.axis('off') 40 | plt.show() 41 | 42 | # Image Filters 43 | Gshift = Fshift * H 44 | G = np.fft.ifftshift(Gshift) 45 | g = np.abs(np.fft.ifft2(G)) 46 | 47 | plt.figure(figsize=(5,5)) 48 | plt.imshow(g, cmap='gray') 49 | plt.axis('off') 50 | plt.show() 51 | 52 | plt.figure(figsize=(5,5)) 53 | plt.imshow(np.log1p(np.abs(Gshift)), cmap='gray') 54 | plt.axis('off') 55 | plt.show() 56 | 57 | plt.figure(figsize=(5,5)) 58 | plt.imshow(np.log1p(np.abs(G)), cmap='gray') 59 | plt.axis('off') 60 | plt.show() 61 | 62 | # Gaussian: High pass filter 63 | HPF = 1 - H 64 | 65 | plt.figure(figsize=(5,5)) 66 | plt.imshow(HPF, cmap='gray') 67 | plt.axis('off') 68 | plt.show() 69 | 70 | # Image Filters 71 | Gshift = Fshift * HPF 72 | G = np.fft.ifftshift(Gshift) 73 | g = np.abs(np.fft.ifft2(G)) 74 | 75 | plt.figure(figsize=(5,5)) 76 | plt.imshow(g, cmap='gray') 77 | plt.axis('off') 78 | plt.show() 79 | 80 | plt.figure(figsize=(5,5)) 81 | plt.imshow(np.log1p(np.abs(Gshift)), cmap='gray') 82 | plt.axis('off') 83 | plt.show() 84 | 85 | plt.figure(figsize=(5,5)) 86 | plt.imshow(np.log1p(np.abs(G)), cmap='gray') 87 | plt.axis('off') 88 | plt.show() 89 | 90 | 91 | -------------------------------------------------------------------------------- /Python#008 Butterworth Filter.py: -------------------------------------------------------------------------------- 1 | # Libraries 2 | import cv2 3 | import numpy as np 4 | import matplotlib.pyplot as plt 5 | 6 | # open the image 7 | f = cv2.imread('rubik.jpg',0) 8 | 9 | # transform image into freq. domain and shifted 10 | F = np.fft.fft2(f) 11 | Fshift = np.fft.fftshift(F) 12 | 13 | plt.imshow(np.log1p(np.abs(Fshift)), cmap='gray') 14 | plt.axis('off') 15 | plt.show() 16 | 17 | # Butterwort Low Pass Filter 18 | M,N = f.shape 19 | H = np.zeros((M,N), dtype=np.float32) 20 | D0 = 10 # cut of frequency 21 | n = 10 # order 22 | for u in range(M): 23 | for v in range(N): 24 | D = np.sqrt((u-M/2)**2 + (v-N/2)**2) 25 | H[u,v] = 1 / (1 + (D/D0)**n) 26 | 27 | plt.imshow(H, cmap='gray') 28 | plt.axis('off') 29 | plt.show() 30 | 31 | # frequency domain image filters 32 | Gshift = Fshift * H 33 | G = np.fft.ifftshift(Gshift) 34 | g = np.abs(np.fft.ifft2(G)) 35 | 36 | plt.imshow(g, cmap='gray') 37 | plt.axis('off') 38 | plt.show() 39 | 40 | # Butterworth High Pass Filter 41 | HPF = np.zeros((M,N), dtype=np.float32) 42 | D0 = 10 43 | n = 1 44 | for u in range(M): 45 | for v in range(N): 46 | D = np.sqrt((u-M/2)**2 + (v-N/2)**2) 47 | HPF[u,v] = 1 / (1 + (D0/D)**n) 48 | 49 | plt.imshow(HPF, cmap='gray') 50 | plt.axis('off') 51 | plt.show() 52 | 53 | # frequency domain image filters 54 | Gshift = Fshift * HPF 55 | G = np.fft.ifftshift(Gshift) 56 | g = np.abs(np.fft.ifft2(G)) 57 | 58 | plt.imshow(g, cmap='gray') 59 | plt.axis('off') 60 | plt.show() 61 | -------------------------------------------------------------------------------- /Python#009 Frequency domain filter Laplacian Filter.py: -------------------------------------------------------------------------------- 1 | # Frequency domain filter: Laplacian filer 2 | import cv2 3 | import numpy as np 4 | import matplotlib.pyplot as plt 5 | 6 | # open and normalized the image 7 | f = cv2.imread('moon.tif',0) 8 | f = f / 255 9 | 10 | plt.figure(dpi=150) 11 | plt.imshow(f, cmap='gray') 12 | plt.axis('off') 13 | plt.show() 14 | 15 | # transform into frequency domain 16 | F = np.fft.fftshift(np.fft.fft2(f)) 17 | 18 | plt.figure(dpi=150) 19 | plt.imshow(np.log1p(np.abs(F)), cmap='gray') 20 | plt.axis('off') 21 | plt.show() 22 | 23 | # Laplacian Filter 24 | P,Q = F.shape 25 | H = np.zeros((P,Q), dtype=np.float32) 26 | for u in range(P): 27 | for v in range(Q): 28 | H[u,v] = -4*np.pi*np.pi*((u-P/2)**2 + (v-Q/2)**2) 29 | 30 | plt.imshow(H, cmap='gray') 31 | plt.axis('off') 32 | plt.show() 33 | 34 | # Laplacian image 35 | Lap = H * F 36 | Lap = np.fft.ifftshift(Lap) 37 | Lap = np.real(np.fft.ifft2(Lap)) 38 | 39 | # convert the Laplacian Image value into range [-1,1] 40 | OldRange = np.max(Lap) - np.min(Lap) 41 | NewRange = 1 - -1 42 | LapScaled = (((Lap - np.min(Lap)) * NewRange) / OldRange) + -1 43 | 44 | plt.figure(dpi=150) 45 | plt.imshow(LapScaled, cmap='gray') 46 | plt.axis('off') 47 | plt.show() 48 | 49 | # image ehancement 50 | c = -1 51 | g = f + c*LapScaled 52 | g = np.clip(g, 0, 1) 53 | 54 | plt.figure(figsize=(5,7),dpi=150) 55 | plt.imshow(g, cmap='gray') 56 | plt.axis('off') 57 | plt.show() 58 | -------------------------------------------------------------------------------- /Python#010 Spatial Domain Image Filter using Laplacian Filter.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | import matplotlib.pyplot as plt 4 | 5 | img = cv2.imread('moon.tif', 0) 6 | 7 | plt.figure(figsize=(8,5), dpi=150) 8 | plt.imshow(img, cmap='gray') 9 | plt.axis('off') 10 | plt.show() 11 | 12 | # kernel 1 13 | kernel = np.array([[0, 1, 0], 14 | [1, -4, 1], 15 | [0, 1, 0]]) 16 | 17 | LaplacianImage = cv2.filter2D(src=img, 18 | ddepth=-1, 19 | kernel=kernel) 20 | 21 | plt.figure(figsize=(8,5), dpi=150) 22 | plt.imshow(LaplacianImage, cmap='gray') 23 | plt.axis('off') 24 | plt.show() 25 | 26 | c = -1 27 | g = img + c*LaplacianImage 28 | 29 | plt.figure(figsize=(8,5), dpi=150) 30 | plt.imshow(g, cmap='gray') 31 | plt.axis('off') 32 | plt.show() 33 | 34 | gClip = np.clip(g, 0, 255) 35 | plt.figure(figsize=(8,5), dpi=150) 36 | plt.imshow(gClip, cmap='gray') 37 | plt.axis('off') 38 | plt.show() 39 | -------------------------------------------------------------------------------- /Python#011 Unsharp Masking and High-boost in spatial domain.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | import matplotlib.pyplot as plt 4 | 5 | # input image f(x,y) 6 | f = cv2.imread('Lenna.png', 0) 7 | f = f / 255 8 | 9 | plt.imshow(f, cmap='gray'); plt.axis('off'); plt.show() 10 | 11 | # blur image 12 | f_blur = cv2.GaussianBlur(src=f, 13 | ksize=(31,31), 14 | sigmaX=0, 15 | sigmaY=0) 16 | 17 | plt.imshow(f_blur, cmap='gray'); plt.axis('off'); plt.show() 18 | 19 | # mask 20 | g_mask = f - f_blur 21 | plt.imshow(g_mask, cmap='gray'); plt.axis('off'); plt.show() 22 | 23 | # unsharp masking 24 | k = 5 25 | g = f + k*g_mask 26 | plt.imshow(g, cmap='gray'); plt.axis('off'); plt.show() 27 | 28 | g = np.clip(g, 0, 1) 29 | plt.imshow(g, cmap='gray'); plt.axis('off'); plt.show() 30 | -------------------------------------------------------------------------------- /Python#012 Unsharp Masking and Highboost Filtering in Frequency Domain.py: -------------------------------------------------------------------------------- 1 | # libraries 2 | import cv2 3 | import numpy as np 4 | import matplotlib.pyplot as plt 5 | 6 | # input image f(x,y) 7 | f = cv2.imread('Lenna.png', 0) 8 | 9 | plt.imshow(f, cmap='gray') 10 | plt.axis('off') 11 | plt.show() 12 | 13 | # input image in frequency domain, F(u,v) 14 | F = np.fft.fftshift(np.fft.fft2(f)) 15 | 16 | plt.imshow(np.log1p(np.abs(F)), cmap='gray') 17 | plt.axis('off') 18 | plt.show() 19 | 20 | # Gaussian Low Pass Filter 21 | M,N = F.shape 22 | H = np.zeros((M,N), dtype=np.float32) 23 | D0 = 10 24 | for u in range(M): 25 | for v in range(N): 26 | D = np.sqrt((u-M/2)**2 + (v-N/2)**2) 27 | H[u,v] = np.exp(-D**2/(2*D0*D0)) 28 | 29 | plt.imshow(H, cmap='gray') 30 | plt.axis('off') 31 | plt.show() 32 | 33 | # create fLP(x,y) (smoothed image) 34 | FLP = H * F 35 | plt.imshow(np.log1p(np.abs(FLP)), cmap='gray') 36 | plt.axis('off') 37 | plt.show() 38 | FLP = np.fft.ifftshift(FLP) 39 | fLP = np.abs(np.fft.ifft2(FLP)) 40 | 41 | plt.imshow(fLP, cmap='gray') 42 | plt.axis('off') 43 | plt.show() 44 | 45 | # create mask g(x,y) 46 | gMask = f - fLP 47 | 48 | plt.imshow(gMask, cmap='gray') 49 | plt.axis('off') 50 | plt.show() 51 | 52 | # unsharp masking 53 | k = 5 54 | g = f + k*gMask 55 | 56 | plt.imshow(g, cmap='gray') 57 | plt.axis('off') 58 | plt.show() 59 | 60 | g = np.clip(g, 0, 255) 61 | plt.imshow(g, cmap='gray') 62 | plt.axis('off') 63 | plt.show() 64 | 65 | # Unsharp Masking in Frequency Domain 66 | G = (1 + k*(1-H))*F 67 | g = np.abs(np.fft.ifft2(np.fft.ifftshift(G))) 68 | plt.imshow(g, cmap='gray') 69 | plt.axis('off') 70 | plt.show() 71 | 72 | g = np.clip(g, 0, 255) 73 | plt.imshow(g, cmap='gray') 74 | plt.axis('off') 75 | plt.show() -------------------------------------------------------------------------------- /Python#013 Edge Detection using Sobel Operator.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import cv2 3 | import matplotlib.pyplot as plt 4 | 5 | # function for displaying image 6 | def display(img): 7 | fig = plt.figure(figsize=(12,10)) 8 | ax = fig.add_subplot(111) 9 | ax.imshow(img,cmap='gray') 10 | ax.axis('off') 11 | 12 | # function for creating an image 13 | def create_img(): 14 | blank_img = np.zeros((200,200)) 15 | font = cv2.FONT_HERSHEY_DUPLEX 16 | cv2.putText(img=blank_img, 17 | text='H', 18 | org=(50,150), 19 | fontFace=font, 20 | fontScale=5, 21 | color=(255,255,255), 22 | thickness=25, 23 | lineType=cv2.LINE_AA) 24 | return blank_img 25 | 26 | # sobel kernel 27 | sobel_x = np.array([[-1, -2, -1], 28 | [ 0, 0, 0], 29 | [ 1, 2, 1]]) 30 | 31 | sobel_y = np.array([[-1, 0, 1], 32 | [-2, 0, 2], 33 | [-1, 0, 1]]) 34 | 35 | # input image 36 | i = create_img() 37 | display(i) 38 | 39 | # partial derivative in x-direction 40 | edge_x = cv2.filter2D(src=i, ddepth=-1, kernel=sobel_x) 41 | display(edge_x) 42 | 43 | edge_x[edge_x != 0] = 255 44 | display(edge_x) 45 | 46 | # partial derivative in y-direction 47 | edge_y = cv2.filter2D(src=i, ddepth=-1, kernel=sobel_y) 48 | display(edge_y) 49 | 50 | edge_y[edge_y != 0] = 255 51 | display(edge_y) 52 | 53 | # combinte the x and y edge 54 | add_edge = edge_x + edge_y 55 | display(add_edge) 56 | 57 | add_edge[add_edge != 0] = 255 58 | display(add_edge) 59 | -------------------------------------------------------------------------------- /Python#014 Add a Gaussian Noise to an Image.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | from scipy.stats.kde import gaussian_kde 4 | import matplotlib.pyplot as plt 5 | 6 | # original image 7 | f = cv2.imread('Lenna.png', 0) 8 | f = f/255 9 | 10 | cv2.imshow('original image', f) 11 | cv2.waitKey(0) 12 | cv2.destroyAllWindows() 13 | 14 | # create gaussian noise 15 | x, y = f.shape 16 | mean = 0 17 | var = 0.01 18 | sigma = np.sqrt(var) 19 | n = np.random.normal(loc=mean, 20 | scale=sigma, 21 | size=(x,y)) 22 | 23 | cv2.imshow('Gaussian noise', n) 24 | cv2.waitKey(0) 25 | cv2.destroyAllWindows() 26 | 27 | # display the probability density function (pdf) 28 | kde = gaussian_kde(n.reshape(int(x*y))) 29 | dist_space = np.linspace(np.min(n), np.max(n), 100) 30 | plt.plot(dist_space, kde(dist_space)) 31 | plt.xlabel('Noise pixel value'); plt.ylabel('Frequency') 32 | plt.show() 33 | 34 | # add a gaussian noise 35 | g = f + n 36 | 37 | cv2.imshow('Corrupted Image', g) 38 | cv2.waitKey(0) 39 | cv2.destroyAllWindows() 40 | 41 | # display all 42 | cv2.imshow('original image', f) 43 | cv2.imshow('Gaussian noise', n) 44 | cv2.imshow('Corrupted Image', g) 45 | 46 | cv2.waitKey(0) 47 | cv2.destroyAllWindows() 48 | -------------------------------------------------------------------------------- /Python#015 How to add an uniform noise to image.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Made Python: https://www.youtube.com/channel/UCfoRD9cQgM8toJ375urVOpQ 3 | ''' 4 | 5 | # libraries 6 | import cv2 7 | import numpy as np 8 | import matplotlib.pyplot as plt 9 | from skimage import img_as_ubyte 10 | 11 | # orginal image 12 | img = cv2.imread('Lenna.png',0) 13 | img = img/255 14 | 15 | cv2.imshow('original image', img) 16 | cv2.waitKey(0) 17 | cv2.destroyAllWindows() 18 | 19 | # uniform noise 20 | x, y = img.shape 21 | a = 0 22 | b = 0.2 23 | n = np.zeros((x,y), dtype=np.float64) 24 | for i in range(x): 25 | for j in range(y): 26 | n[i][j] = np.random.uniform(a,b) 27 | 28 | cv2.imshow('noise', n) 29 | cv2.waitKey(0) 30 | cv2.destroyAllWindows() 31 | 32 | # add noise to image 33 | noise_img = img + n 34 | noise_img = np.clip(noise_img, 0, 1) 35 | 36 | cv2.imshow('image with noise', noise_img) 37 | cv2.imshow('original image', img) 38 | cv2.waitKey(0) 39 | cv2.destroyAllWindows() 40 | 41 | # hitogram: original image 42 | plt.hist(img.flat) 43 | plt.xlim([0,1]); plt.ylim([0,60000]) 44 | plt.xlabel('pixel value'); plt.ylabel('frequency') 45 | plt.show() 46 | 47 | # histogram: noise 48 | plt.hist(n.flat) 49 | plt.xlim([0,1]); plt.ylim([0,60000]) 50 | plt.xlabel('noise pixel value'); plt.ylabel('frequency') 51 | plt.show() 52 | 53 | # hitogram: noise image 54 | plt.hist(noise_img.flat) 55 | plt.xlim([0,1]); plt.ylim([0,60000]) 56 | plt.xlabel('pixel value'); plt.ylabel('frequency') 57 | plt.show() 58 | 59 | # save the image 60 | cv2.imwrite('uniform noise.jpg', img_as_ubyte(n)) #uint8 61 | cv2.imwrite('noise image.jpg', img_as_ubyte(noise_img)) 62 | cv2.imwrite('lenna grayscale.jpg', img_as_ubyte(img)) 63 | -------------------------------------------------------------------------------- /Python#016 Manually Add a Salt and Paper Noise.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Made Python: https://www.youtube.com/channel/UCfoRD9cQgM8toJ375urVOpQ 3 | ''' 4 | 5 | # libraries 6 | import cv2 7 | import numpy as np 8 | 9 | # orginal image 10 | img = cv2.imread('Lenna.png',0) 11 | img = img/255 12 | 13 | cv2.imshow('original image', img) 14 | cv2.waitKey(0) 15 | cv2.destroyAllWindows() 16 | 17 | # blank image 18 | x,y = img.shape 19 | g = np.zeros((x,y), dtype=np.float32) 20 | 21 | # salt and pepper amount 22 | pepper = 0.1 23 | salt = 0.95 24 | 25 | # create salt and peper noise image 26 | for i in range(x): 27 | for j in range(y): 28 | rdn = np.random.random() 29 | if rdn < pepper: 30 | g[i][j] = 0 31 | elif rdn > salt: 32 | g[i][j] = 1 33 | else: 34 | g[i][j] = img[i][j] 35 | 36 | cv2.imshow('image with noise', g) 37 | cv2.waitKey(0) 38 | cv2.destroyAllWindows() 39 | 40 | # (optional) save the image 41 | from skimage import img_as_ubyte 42 | cv2.imwrite('5percent.jpg', img_as_ubyte(g)) -------------------------------------------------------------------------------- /Python#017 Denoising an Image using Mean and Median Filter.py: -------------------------------------------------------------------------------- 1 | """ 2 | @author: Made Python 3 | https://www.youtube.com/channel/UCfoRD9cQgM8toJ375urVOpQ/about 4 | """ 5 | 6 | import cv2 7 | import numpy as np 8 | from skimage import img_as_ubyte 9 | 10 | ## original image 11 | img = cv2.imread('Lenna.png', 0) 12 | img = img/img.max() # normalize the pixel value (0~1) 13 | 14 | ## noise image 15 | # Gaussian Noise 16 | # ============================================================================= 17 | # x, y = img.shape 18 | # mean = 0 19 | # var = 0.01 20 | # sigma = np.sqrt(var) 21 | # n = np.random.normal(loc=mean, 22 | # scale=sigma, 23 | # size=(x,y)) 24 | # img_noise = img + n 25 | # ============================================================================= 26 | 27 | # Salt and Pepper Noise 28 | x,y = img.shape 29 | g = np.zeros((x,y), dtype=np.float32) 30 | pepper = 0.1 31 | salt = 0.95 32 | for i in range(x): 33 | for j in range(y): 34 | rdn = np.random.random() 35 | if rdn < pepper: 36 | g[i][j] = 0 37 | elif rdn > salt: 38 | g[i][j] = 1 39 | else: 40 | g[i][j] = img[i][j] 41 | 42 | img_noise = g 43 | 44 | # preview the images 45 | cv2.imshow('Original Image', img) 46 | cv2.imshow('Image + Noise', img_noise) 47 | 48 | cv2.waitKey(0) 49 | cv2.destroyAllWindows() 50 | 51 | ## denoise image 52 | # mean filter (average) 53 | m = 5 54 | n = 5 55 | denoise_mean = cv2.blur(img_noise, (m,n)) 56 | 57 | # median filter 58 | img_noise_median = np.clip(img_noise, -1, 1) #pixel value range 59 | img_noise_median = img_as_ubyte(img_noise_median) #convert to uint8 60 | denoise_median = cv2.medianBlur(img_noise_median, 5) 61 | 62 | # preview the images 63 | cv2.imshow('Original Image', img) 64 | cv2.imshow('Image + Noise', img_noise) 65 | cv2.imshow('Denoise Mean', denoise_mean) 66 | cv2.imshow('Denoise Median', denoise_median) 67 | 68 | cv2.waitKey(0) 69 | cv2.destroyAllWindows() 70 | 71 | # (optional) save the result 72 | cv2.imwrite('Denoise mean.jpg', img_as_ubyte(denoise_mean)) 73 | cv2.imwrite('Denoise median.jpg', img_as_ubyte(denoise_median)) -------------------------------------------------------------------------------- /Python#018 Create a Motion Blur Image.py: -------------------------------------------------------------------------------- 1 | """ 2 | @author: Made Python 3 | """ 4 | import numpy as np 5 | import cv2 6 | from skimage import img_as_ubyte 7 | import matplotlib.pyplot as plt 8 | 9 | # f(x,y), input image in spatial domain 10 | f = cv2.imread('License Plate.jpg', 0) 11 | 12 | f = f/f.max() # normalize 13 | 14 | # F(u,v), image in frequency domain 15 | F = np.fft.fft2(f) 16 | 17 | plt.imshow(np.log1p(np.abs(F)), cmap='gray') 18 | plt.axis('off') 19 | plt.show() 20 | 21 | # H(u,v), motion blur function in frequency domain 22 | # Create matrix H (motion blur function H(u,v)) 23 | M,N = F.shape 24 | H = np.zeros((M+1,N+1), dtype=np.complex128) # +1 to avoid zero division 25 | 26 | # Motion blur parameters 27 | T = 0.5 # duration of exposure 28 | a = 0.05 # vertical motion 29 | b = 0 # horizontal motion 30 | 31 | # Fill matrix H 32 | for u in range(1,M+1): 33 | for v in range(1,N+1): 34 | s = np.pi*(u*a + v*b) 35 | H[u,v] = (T/s) * np.sin(s) * np.exp(-1j*s) 36 | 37 | # index slicing 38 | H = H[1:,1:] 39 | 40 | plt.imshow(np.log1p(np.abs(H)), cmap='gray') 41 | plt.axis('off') 42 | plt.show() 43 | 44 | # G(u,v), blurred image in frequency domain 45 | G = H * F 46 | 47 | plt.imshow(np.log1p(np.abs(G)), cmap='gray') 48 | plt.axis('off') 49 | plt.show() 50 | 51 | # g(x,y), blurred image in spatial domain 52 | g = np.fft.ifft2(G) 53 | g = np.abs(g) 54 | 55 | g = img_as_ubyte(g) # if you want to save the image 56 | 57 | # display the result 58 | cv2.imshow('original', f) 59 | cv2.imshow('blur', g) 60 | cv2.waitKey(0) 61 | cv2.destroyAllWindows() -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # digital-image-processing 2 | A python code of digital image processing video series on my YouTube channel 3 | https://www.youtube.com/channel/UCfoRD9cQgM8toJ375urVOpQ/featured 4 | --------------------------------------------------------------------------------