import cv2 import numpy as np import os from tkinter import Tk, filedialog def select_image(): Tk().withdraw() # 隱藏主視窗 file_path = filedialog.askopenfilename( title="選擇影像檔案", filetypes=[("影像檔案", "*.png;*.jpg;*.jpeg;*.bmp")] ) return file_path def read_image_with_unicode_path(image_path): with open(image_path, 'rb') as file: binary_data = np.asarray(bytearray(file.read()), dtype=np.uint8) image = cv2.imdecode(binary_data, cv2.IMREAD_COLOR) return image def save_image(output_path, image): # 儲存影像到指定路徑 cv2.imwrite(output_path, image) print(f"影像已儲存至:{output_path}") def detect_lines_with_hough(image): # 二值化處理 _, binary_image = cv2.threshold(image, 68, 255, cv2.THRESH_BINARY) # 儲存二值化影像 binary_image_path = os.path.join(r"E:\AP", f"binary.png") save_image(binary_image_path, binary_image) # 霍夫直線偵測 lines = cv2.HoughLinesP(binary_image, 1, np.pi / 180, threshold=100, minLineLength=1300, maxLineGap=50) # 在原影像上繪製直線 line_image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR) # 將灰階影像轉為 BGR 以繪製彩色直線 if lines is not None: for line in lines: x1, y1, x2, y2 = line[0] cv2.line(line_image, (x1, y1), (x2, y2), (0, 0, 255), 2) return line_image def process_image(image_path): # 讀取影像 image = read_image_with_unicode_path(image_path) if image is None: print("無法讀取影像") return # 轉換為灰階影像 gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # 執行霍夫直線偵測(前處理為二值化) line_image = detect_lines_with_hough(gray_image) # 取得輸出路徑 directory = os.path.dirname(r"E:\AP\img0120") gray_image_path = os.path.join(directory, f"gray.png") lines_image_path = os.path.join(directory, f"lines.png") # 儲存影像 save_image(gray_image_path, gray_image) save_image(lines_image_path, line_image) if __name__ == "__main__": file_path = select_image() if file_path: process_image(file_path) else: print("未選擇影像檔案")