-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathopencv_binary_thresholding.py
More file actions
51 lines (37 loc) · 1.3 KB
/
Copy pathopencv_binary_thresholding.py
File metadata and controls
51 lines (37 loc) · 1.3 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
# Import OpenCV library
import cv2
# --------------------------------
# Step 1: Load the image
# --------------------------------
# cv2.imread() reads the image from the specified file path
# Replace "imageName.png" with your actual image file
img = cv2.imread("imageName.png")
# --------------------------------
# Step 2: Convert image to grayscale
# --------------------------------
# Thresholding works best on grayscale images
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# --------------------------------
# Step 3: Apply Binary Threshold
# --------------------------------
# cv2.threshold() converts grayscale image into binary image
# 170 = threshold value
# 255 = maximum pixel value
# cv2.THRESH_BINARY = binary thresholding method
threshold_img = cv2.threshold(gray_img, 170, 255, cv2.THRESH_BINARY)[1]
# --------------------------------
# Step 4: Display images
# --------------------------------
# Show original image
cv2.imshow("Original Image", img)
# Show thresholded image
cv2.imshow("Threshold Image", threshold_img)
# --------------------------------
# Step 5: Wait for key press
# --------------------------------
# waitKey(0) waits until any key is pressed
cv2.waitKey(0)
# --------------------------------
# Step 6: Close all windows
# --------------------------------
cv2.destroyAllWindows()