-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path35 Morphological Transformations.py
73 lines (48 loc) · 1.83 KB
/
35 Morphological Transformations.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
"""
@author: Osama Shakeel
#-------------Morphological Transformations-----------------------
Morphological transformations are some simple operations based on the image shape.
It is normally performed on binary images.
It needs two inputs, 1)- original image, 2)- structuring element(kernel).
Two basic Morphological Transformations are 1) - Erosion and 2) - Dilation
"""
import cv2
import numpy as np
img = cv2.imread('D:\\music\\col_balls.jpg',0)
_,mask= cv2.threshold(img,230,255,cv2.THRESH_BINARY_INV)
"""
kernal slides through all the image and all the pixel
from the original image conside 1 only if kernal's pixel is 1
"""
kernel = np.ones((5,5),np.uint8)# 5x5 kernel with full of ones.
"""
Dilation --
It is just opposite of erosion.
Here, a pixel element is ‘1’ if atleast one pixel under the kernel is ‘1’
So it inc. the white region in the image or size of foreground object in.
Normally, in cases like noise removal, erosion is followed by dilation.
Because, erosion removes white noises, but it also shrinks our object.
"""
d = cv2.dilate(mask,kernel) #iterations = 2 (optional parameters) iterations = 2
cv2.imshow("dilate==",d)
"""
Erosion---
it erodes away the boundaries of foreground object
"""
kernel = np.ones((5,5),np.uint8)# 5x5 kernel with full of ones.
e = cv2.erode(mask, kernel) #optional parameters iterations = 2
cv2.imshow("img",img)
cv2.imshow("ker=",kernel)
cv2.imshow("mask==",mask)
cv2.imshow("erosion==",e)
#if you want then plot it
from matplotlib import pyplot as plt
titles = ["img","mask","erosion","dilation"]
images = [img,mask,e,d]
for i in range(4):
plt.subplot(2, 2, i+1), plt.imshow(images[i], 'gray')
plt.title(titles[i])
plt.xticks([]),plt.yticks([])
plt.show()
cv2.waitKey(0)
cv2.destroyAllWindows()