Threshold.py
2.4 KB
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
import sys
import cv2
import numpy as np
from matplotlib import pyplot as plt
def ThresholdEverything(img):
ret,th1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
th2 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,11,2)
th3 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2)
titles = ['Original Image', 'Global Thresholding (v = 127)',
'Adaptive Mean Thresholding', 'Adaptive Gaussian Thresholding']
images = [img, th1, th2, th3]
for i in xrange(4):
plt.subplot(2,2,i+1),plt.imshow(images[i],'gray')
plt.title(titles[i])
plt.xticks([]),plt.yticks([])
plt.show()
cv2.imwrite('Threshold.png', th1)
return images
def GlobalThresholding(img):
ret,th1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
plt.plot(), plt.imshow(th1, 'gray')
plt.title('Global Thresholding (v = 127)')
plt.show()
return th1
def AdaptiveMeanThresholding(img):
th2 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,11,2)
plt.plot(), plt.imshow(th2, 'gray')
plt.title('Adaptive Mean Thresholding')
plt.show()
return th2
def AdaptiveGaussianThresholding(img):
th3 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2)
plt.plot(), plt.imshow(th3, 'gray')
plt.title('Adaptive Gaussian Thresholding')
plt.show()
return th3
def ThresholdChoiceProcessing(img, choice):
if choice == '1':
img = GlobalThresholding(img)
return img
elif choice == '2':
img = AdaptiveMeanThresholding(img)
return img
elif choice == '3':
img = AdaptiveGaussianThresholding(img)
return img
elif choice == '4':
img = ThresholdEverything(img)
return img
else:
return
def ThresholdChoice() :
image = None
print('\t\tThreshold Menu\n')
while (image is None):
if sys.version_info >= (3, 0):
image = str(input('\tImage to use ? By default couleur.png \n'))
else:
image = str(raw_input('\tImage to use ? By default couleur.png \n'))
if not image:
image = 'couleur.png'
image = cv2.imread(str(image), 0)
img = cv2.medianBlur(image,5)
print ('\t1. Global Thresholding\n\t2. Adaptive Mean Thresholding\n\t3. Adaptive Gaussian Thresholding\n\t4. Everything\n')
if sys.version_info >= (3, 0):
choice = input('\n\tMultiple choices possible\n')
else:
choice = raw_input('\n\tMultiple choices possible\n')
for i in range (0, len(choice)):
img = image.copy()
img = ThresholdChoiceProcessing(img, choice[i])
return