介紹 OpenCV 的基本安裝、影像讀取、攝影機擷取、灰階、邊緣偵測、輪廓、臉部辨識與課堂應用。
很適合搭配 Raspberry Pi 與 1080p Web CAM 進行影像處理入門教學。
python3 -m venv venv
source venv/bin/activate
python3 -m pip install opencv-python
import cv2
img = cv2.imread('test.jpg')
cv2.imshow('Image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
import cv2
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if not ret:
break
cv2.imshow('Webcam', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
import cv2
img = cv2.imread('test.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 100, 200)
cv2.imshow('Gray', gray)
cv2.imshow('Edges', edges)
cv2.waitKey(0)
cv2.destroyAllWindows()
import cv2
img = cv2.imread('test.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imwrite('gray.jpg', gray)
import cv2
img = cv2.imread('test.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, contours, -1, (0,255,0), 2)
cv2.imshow('Contours', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
import cv2
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if not ret:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.1, 4)
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x,y), (x+w, y+h), (0,255,0), 2)
cv2.imshow('Face Detection', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
| 問題 | 原因 | 解法 |
|---|---|---|
| 抓不到相機 | 索引錯誤或裝置未偵測 | 確認 /dev/video0 與 Webcam 是否存在 |
| 無法顯示視窗 | 圖形環境限制 | 確認桌面環境或改用存檔測試 |
| 模組找不到 | OpenCV 未安裝到正確環境 | 重新確認 venv 與 pip 安裝位置 |