图像的阈值处理

demo1

# 二值化处理黑白渐变图
import cv2
img = cv2.imread("./img.png", 0)
# 二值化处理
t1, dst = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
cv2.imshow("img", img)
cv2.imshow("dst", dst)
cv2.waitKey()
cv2.destroyAllWindows()

demo2

# 二值化处理黑白渐变图
import cv2
img = cv2.imread("./img.png", 0)
# 二值化处理
t1, dst1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
t2, dst2 = cv2.threshold(img, 210, 255, cv2.THRESH_BINARY)
cv2.imshow("img", img)
cv2.imshow("dst1", dst1)
cv2.imshow("dst2", dst2)
cv2.waitKey()
cv2.destroyAllWindows()

demo3

# 二值化处理黑白渐变图
import cv2
img = cv2.imread("./img.png", 0)
# 二值化处理
t1, dst1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
t2, dst2 = cv2.threshold(img, 210,150, cv2.THRESH_BINARY)
cv2.imshow("img", img)
cv2.imshow("dst1", dst1)
cv2.imshow("dst2", dst2)
cv2.waitKey()
cv2.destroyAllWindows()

demo4

# 反二值化处理
import cv2
img = cv2.imread("./img.png", 0)
# 二值化处理
t1, dst1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
t2, dst2 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY_INV)
cv2.imshow("img", img)
cv2.imshow("dst1", dst1)
cv2.imshow("dst2", dst2)
cv2.waitKey()
cv2.destroyAllWindows()

demo5

# 零处理---低于阈值0处理
import cv2
img = cv2.imread("./img.png", 1)
# 二值化处理
t1, dst1 = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO)
cv2.imshow("img", img)
cv2.imshow("dst1", dst1)
cv2.imwrite("./myimg.jpg", dst1)
cv2.waitKey()
cv2.destroyAllWindows()

demo6

# 零处理---高于阈值0处理
import cv2
img = cv2.imread("./img.png", 0)
# 二值化处理
t1, dst1 = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO_INV)
cv2.imshow("img", img)
cv2.imshow("dst1", dst1)
cv2.imwrite("./myimg.jpg", dst1)
cv2.waitKey()
cv2.destroyAllWindows()

demo7

# 截断处理---大于阈值阈值处理
import cv2
img = cv2.imread("./img.png")
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
athdMEAM = cv2.adaptiveThreshold(img_gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 5, 3)
athdGAUS = cv2.adaptiveThreshold(img_gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 5, 3)
cv2.imshow("athdMEAM", athdMEAM)
cv2.imshow("athdGAUS", athdGAUS)
# cv2.imwrite("./myimg.jpg", dst1)
cv2.waitKey()
cv2.destroyAllWindows()

demo8

# OTsu方法
import cv2
img = cv2.imread("./img.png", 1)
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

t1, dst1 = cv2.threshold(img_gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
cv2.putText(dst1, "best threshold" + str(t1), (0, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 2)

cv2.imshow("dst1", dst1)
cv2.waitKey()
cv2.destroyAllWindows()