import cv2 import numpy as np def find_line(image): if image is None: print("Error: Unable to load image.") exit() gray_frame = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) blurred_image = cv2.GaussianBlur(gray_frame, (9, 9), 0) ret, gray_frame = cv2.threshold(blurred_image, 50, 255, cv2.THRESH_BINARY) cv2.imshow("binary", gray_frame) # edges = cv2.Canny(blurred_image, 50, 150, apertureSize=3) # 应用边缘检测 edges = cv2.Canny(gray_frame, 200, 400, apertureSize=3) # 使用标准霍夫变换检测直线 # 使用标准霍夫变换检测直线 lines = cv2.HoughLines(edges, rho=3, theta=np.pi / 180, threshold=200) # 绘制检测到的直线 if lines is not None: for line in lines: rho, theta = line[0] a = np.cos(theta) b = np.sin(theta) x0 = a * rho y0 = b * rho x1 = int(x0 + 1000 * (-b)) y1 = int(y0 + 1000 * (a)) x2 = int(x0 - 1000 * (-b)) y2 = int(y0 - 1000 * (a)) cv2.line(image, (x1, y1), (x2, y2), (0, 0, 255), 2) if __name__ == '__main__': # 读取图像 img = cv2.imread("images/trans/subRawImg.jpg") find_line(img) # 显示结果 cv2.imshow("Detected Lines", img) cv2.waitKey(0) cv2.destroyAllWindows()