import cv2
def find_optimal_threshold(image):
# 将图像转为灰度图
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 使用Otsu阈值法计算最佳阈值
_, threshold = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
return threshold
# 替换为你的图像路径
image_path = 'path/to/your/image.jpg'
# 读取图像
image = cv2.imread(image_path)
# 寻找最佳阈值
optimal_threshold = find_optimal_threshold(image)
# 显示图像和最佳阈值结果
cv2.imshow("Original", image)
cv2.imshow("Optimal Threshold", optimal_threshold)
cv2.waitKey(0)
cv2.destroyAllWindows()