commit 4b9ade675939e10b4e81656f8f62c4d33d7f4060 Author: snsd0805 Date: Sat Dec 16 03:27:02 2023 +0800 feat: use celephone's camera to detect paper diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..60baa9c --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +data/* diff --git a/test.py b/test.py new file mode 100644 index 0000000..3fb88cb --- /dev/null +++ b/test.py @@ -0,0 +1,53 @@ + +import cv2 + +# 設定連接到 Android 手機的相機 +cap = cv2.VideoCapture(0) # 0 表示第一個相機(通常是後置相機),若是前置相機,可以使用 1 +cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1920) # 設定寬度 +cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080) # 設定高度 + + +while True: + ret, frame = cap.read() # 讀取影片幀 + + if not ret: + break + + # 預處理影像(例如:轉為灰度) + gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) + + # 偵測邊緣 + edges = cv2.Canny(gray, 100, 200) + + # 偵測輪廓 + contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) + + # 找到最大的輪廓 + max_contour = max(contours, key=cv2.contourArea) + + # 找到輪廓的近似多邊形 + epsilon = 0.05 * cv2.arcLength(max_contour, True) + approx = cv2.approxPolyDP(max_contour, epsilon, True) + + # 繪製多邊形 + if len(approx) == 4: # 確保是四個角點 + for point in approx: + print(point) + x, y = point[0] + cv2.circle(frame, (x, y), 5, (0, 0, 255), -1) # 在角點位置畫紅色圓圈 + + cv2.drawContours(frame, [approx], -1, (0, 255, 0), 2) # 繪製輪廓 + print() + + # 顯示結果 + cv2.imshow('Paper Detection', frame) + # 按下 'q' 鍵退出迴圈 + if cv2.waitKey(33) & 0xFF == ord('q'): # 等待 33ms (1秒 = 1000ms, 1秒顯示30幀) + break + + + +cap.release() +cv2.destroyAllWindows() + +