Now we add the Gaussian blur function to the ImageProcessing class.
1 def blur(self, ksize=(1,1), image=None):
2 if image is None:
3 image = self.image
4 if ksize[0] % 2 == 0:
5 ksize = (ksize[0] + 1, ksize[1])
6 if ksize[1] % 2 == 0:
7 ksize = (ksize[0], ksize[1] + 1)
8 result = cv2.GaussianBlur(image,ksize, cv2.BORDER_DEFAULT)
9 return result
Explanations:
Line 1 Define the blur() function, pass ksize as parameter.
Line 4 – 7 ksize must be odd numbers, check ksize if not odd then change it to odd.
Line 8 Invoke cv2.GaussianBlur() function.
BlurImage.py file has the source codes to perform the Gaussian blur, a trackbar is added to change the kernel size, by changing the kernel size we can observe how the blurring effects are different. In this example a square kernel is used, meaning the width and height are equal. Feel free to modify the codes to use a rectangle kernel and observe the blurring effects.
1 import cv2
2 import common.ImageProcessing as ip
3
4 def change_ksize(value):
5 global ksize
6 if value % 2 == 0:
7 ksize = (value+1, value+1)
8 else:
9 ksize = (value, value)
10
11 if __name__ == “__main__”:
12 global ksize
13 ksize = (5,5)
14 iproc = ip.ImageProcessing(“Original”,
“../res/flower003.jpg”)
15 iproc.show()
16
17 cv2.namedWindow(“Gaussian Blur”)
18 cv2.createTrackbar(“K-Size”, “Blur”, 5, 21,
change_ksize)
19
20 while True:
21 blur = iproc.blur(ksize)
22 iproc.show(“Blur”, blur)
23
24 ch = cv2.waitKey(10)
25 # Press ‘ESC’ to exit
if (ch & 0xFF) == 27:
26 break
27 # Press ‘s’ to save
elif ch == ord(‘s’):
28 filepath = “C:/temp/blend_image.png”
29 cv2.imwrite(filepath, blur)
30 print(“File saved to “ + filepath)
31 cv2.destroyAllWindows()
Explanations:
Line 4 – 9 Trackbar callback function, get kernel size from trackbar, and change it to odd number if it’s not.
Line 14 – 15 Instantiate the ImageProcessing class with an image and show it as original image.
Line 17 – 18 Create a trackbar in another window called “Gaussian Blur”.
Line 21 Call blur() function defined above in ImageProcessing class, pass the kernel size as a parameter.
Line 22 Show the blurred image in the “Gaussian Blur” window.
Figure 4 is the result, as the K-Size trackbar is changing, the degree of blurring is also changing in real-time.
0 comments:
Post a Comment