-
Notifications
You must be signed in to change notification settings - Fork 0
/
tools.py
120 lines (81 loc) · 2.65 KB
/
tools.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
import cv2
from base64 import b64encode
def read_image(img_path):
img = cv2.imread(img_path)
return img
def save_image(img):
cv2.imwrite('C:/Users/rafik/Desktop/PhotoSaved/img.jpg', img)
def img_enc(img):
_, image = cv2.imencode('.jpeg', img)
bit_img = image.tobytes()
return b64encode(bit_img).decode('utf-8')
def initialize(img):
return img[0:2]
# THRESHOLD
# ***************************
def to_gray_scale(img):
if img.shape[-1] == 3:
return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
else:
return img
def to_binary_inv(img, thresh=100):
if img.shape[-1] == 3:
img = to_gray_scale(img)
_, img = cv2.threshold(img, thresh, 255, cv2.THRESH_BINARY_INV)
else:
_, img = cv2.threshold(img, thresh, 255, cv2.THRESH_BINARY_INV)
return img
def to_truncate(img, thresh=100):
if img.shape[-1] == 3:
img = to_gray_scale(img)
_, img = cv2.threshold(img, thresh, 255, cv2.THRESH_TRUNC)
else:
_, img = cv2.threshold(img, thresh, 255, cv2.THRESH_TRUNC)
return img
def to_zero(img, thresh=100):
if img.shape[-1] == 3:
img = to_gray_scale(img)
_, img = cv2.threshold(img, thresh, 255, cv2.THRESH_TOZERO)
else:
_, img = cv2.threshold(img, thresh, 255, cv2.THRESH_TOZERO)
return img
def to_zero_inv(img, thresh=100):
if img.shape[-1] == 3:
img = to_gray_scale(img)
_, img = cv2.threshold(img, thresh, 255, cv2.THRESH_TOZERO_INV)
else:
_, img = cv2.threshold(img, thresh, 255, cv2.THRESH_TOZERO_INV)
return img
# MORPHOLOGY
# *******************
# Element structurant
iterations = 1
elt_structurant = cv2.getStructuringElement(cv2.MORPH_CROSS, (5, 5))
# erosion
# **********
def erosion(img, iterations=iterations):
return cv2.erode(img, elt_structurant, iterations=iterations)
# dilatation
# ************
def dilatation(img, iterations=iterations):
return cv2.dilate(img, elt_structurant, iterations=iterations)
# ouverture
# *********
def open(img, iterations=iterations):
return cv2.morphologyEx(img, cv2.MORPH_OPEN, elt_structurant, iterations=iterations)
# fermeture
# **********
def close(img, iterations=iterations):
return cv2.morphologyEx(img, cv2.MORPH_CLOSE, elt_structurant, iterations=iterations)
# gradient
# **********************
def gradient(img, iterations=iterations):
return cv2.morphologyEx(img, cv2.MORPH_GRADIENT, elt_structurant, iterations=iterations)
# FILTERS
# ********
def median_blur(img):
return cv2.medianBlur(img, 5)
def gaussian_blur(img):
return cv2.GaussianBlur(img, (5, 5), 0)
def edge_detect(img):
return cv2.Canny(img, 100, 200)