pythonimport cv2import numpy as np 完整预处理流程def image_preprocess(img_path, target_size=(640, 480), thresh=127):# 1. 读取图像img = cv2.imread(img_path)if img is None:print("错误:无法读取图像,请检查路径是否正确!")return None# 2. 高斯去噪blur_img = cv2.GaussianBlur(img, ksize=(5,5), sigmaX=1.5)# 3. 尺寸调整resized_img = cv2.resize(blur_img, target_size, interpolation=cv2.INTER_LINEAR)# 4. 灰度化gray_img = cv2.cvtColor(resized_img, cv2.COLOR_BGR2GRAY)# 5. 二值化ret, binary_img = cv2.threshold(gray_img, thresh, 255, cv2.THRESH_BINARY)# 返回处理后的图像return img, binary_img# 调用函数,替换为你的图片路径img_path = "test.jpg"original_img, processed_img = image_preprocess(img_path)# 显示结果if processed_img is not None:cv2.imshow("原始图像", original_img)cv2.imshow("预处理后图像", processed_img)cv2.waitKey(0)cv2.destroyAllWindows() |