图像的阈值处理
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
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
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.waitKey()
cv2.destroyAllWindows()
demo8
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()