Basic Thresholding – OpenCV 3.4 with python 3 Tutorial 10
Threshold:
[python]
import cv2
import numpy as np
img = cv2.imread("black_to_white.jpeg", cv2.IMREAD_GRAYSCALE)
_, threshold_binary = cv2.threshold(img, 128, 255, cv2.THRESH_BINARY)
_, threshold_binary_inv = cv2.threshold(img, 128, 255, cv2.THRESH_BINARY_INV)
_, threshold_trunc = cv2.threshold(img, 128, 255, cv2.THRESH_TRUNC)
_, threshold_to_zero = cv2.threshold(img, 12, 255, cv2.THRESH_TOZERO)
cv2.imshow("Image", img)
cv2.imshow("th binary", threshold_binary)
cv2.imshow("th binary inv", threshold_binary_inv)
cv2.imshow("th trunc", threshold_trunc)
cv2.imshow("th to zero", threshold_to_zero)
cv2.waitKey(0)
cv2.destroyAllWindows()
[/python]
Threshold with Trackbar:
[python]
import cv2
import numpy as np
def nothing(x):
pass
img = cv2.imread("red_panda.jpg", cv2.IMREAD_GRAYSCALE)
cv2.namedWindow("Image")
cv2.createTrackbar("Threshold value", "Image", 128, 255, nothing)
while True:
value_threshold = cv2.getTrackbarPos("Threshold value", "Image")
_, threshold_binary = cv2.threshold(img, value_threshold, 255, cv2.THRESH_BINARY)
_, threshold_binary_inv = cv2.threshold(img, value_threshold, 255, cv2.THRESH_BINARY_INV)
_, threshold_trunc = cv2.threshold(img, value_threshold, 255, cv2.THRESH_TRUNC)
_, threshold_to_zero = cv2.threshold(img, value_threshold, 255, cv2.THRESH_TOZERO)
_, threshold_to_zero_inv = cv2.threshold(img, value_threshold, 255, cv2.THRESH_TOZERO_INV)
cv2.imshow("Image", img)
cv2.imshow("th binary", threshold_binary)
cv2.imshow("th binary inv", threshold_binary_inv)
cv2.imshow("th trunc", threshold_trunc)
cv2.imshow("th to zero", threshold_to_zero)
cv2.imshow("th to zero inv", threshold_to_zero_inv)
key = cv2.waitKey(100)
if key == 27:
break
cv2.destroyAllWindows()
[/python]
Files:

Hi there, I’m the founder of Pysource.
I’m a Computer Vision Consultant, developer and Course instructor.
I help Companies and Freelancers to easily and efficiently build Computer Vision Software.

Learn to build Computer Vision Software easily and efficiently.
This is a FREE Workshop where I'm going to break down the 4 steps that are necessary to build software to detect and track any object.
Sign UP for FREE