-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_thresholding.py
More file actions
72 lines (53 loc) · 1.45 KB
/
binary_thresholding.py
File metadata and controls
72 lines (53 loc) · 1.45 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
"""
Binary Thresholding
By Carlos Santiago Bañón
binary_thresholding.py
An implementation of the binary image thresholding algorithm.
"""
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.image as mpimg
import sys
from skimage.color import rgb2gray
def binary_threshold(img, threshold):
"""
Perform binary thresholding.
:img: the original grayscale image.
:threshold: the threshold value.
"""
# Flatten the image.
flat = np.ndarray.flatten(img)
# Perform the threshold.
for i in range(flat.shape[0]):
if (flat[i] * 255) > threshold:
flat[i] = 255
else:
flat[i] = 0
# Reshape the image.
thresh_img = np.reshape(flat, (img.shape[0], img.shape[1]))
return thresh_img
# Load the image.
image_path = str(sys.argv[1])
img = mpimg.imread(image_path)
# Show the image.
plt.imshow(img, cmap='gray')
plt.show()
# Convert to a grayscale image.
grayscale = rgb2gray(img)
# Show the grayscale image.
plt.imshow(grayscale, cmap='gray')
plt.show()
# Get a histogram for the image.
histogram, bin_edges = np.histogram(grayscale, bins=256, range=(0, 1))
# Show the histogram.
plt.figure()
plt.xlabel("Value")
plt.ylabel("Number of Pixels")
plt.xlim([0.0, 255.0])
plt.plot((bin_edges[0:-1] * 255), histogram)
plt.show()
# Perform Otsu thresholding.
thresh_img = binary_threshold(grayscale, 185)
# Show the thresholded image.
plt.imshow(thresh_img, cmap='gray')
plt.show()