# 安裝OpenCV
更新系統
$ sudo apt update && sudo apt upgrade -y
使用apt安裝
$ sudo apt install -y python3-opencv
### GPU記憶體更改


reboot後

### V4L2(Video4Linux2) and MMAL (Multi-Media Abstraction Layer)
在 Raspberry Pi OS Bullseye 之前,官方使用 raspivid 和 raspistill 來存取 Raspberry Pi Camera,這些工具基於 MMAL (Multi-Media Abstraction Layer) 和 V4L2 (Video4Linux2)。
但 從 Bullseye 版本開始(2021年後),Raspberry Pi 完全移除了 MMAL,轉而改用 libcamera 來管理相機。
### Picamera2(Python 版 libcamera)
官方為了讓 Python 開發者方便使用 libcamera,推出了 Picamera2,這是 Raspberry Pi 官方推薦的 Python API。
使用V4L2(現在已未使用)
```python=
cap = cv2.VideoCapture(0, cv2.CAP_V4L2)
```
使用libcamera
```python=
from picamera2 import Picamera2
picam2 = Picamera2()
picam2.preview_configuration.main.size = (640, 480) # Set resolution
picam2.preview_configuration.main.format = "RGB888"
picam2.configure("preview")
picam2.start()
while True:
frame = picam2.capture_array()
```
## 下載 Haar Cascades(OpenCV 內建的人臉辨識模型)
```bash
wget -O haarcascade_frontalface_default.xml https://github.com/opencv/opencv/raw/master/data/haarcascades/haarcascade_frontalface_default.xml
```
此檔案須跟程式碼在同個資料夾(路徑)
### 輸出影像
影像格式未設定


### Code
:::spoiler face_detection.py
```python=
import cv2
from picamera2 import Picamera2
import numpy as np
# Load Haar Cascade for face detection
cascPath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
if faceCascade.empty():
print("Error: Could not load cascade file. Check the file path.")
exit()
# Initialize Picamera2
picam2 = Picamera2()
picam2.preview_configuration.main.size = (640, 480) # Set resolution to 640x480
picam2.preview_configuration.main.format = "RGB888" # Set image format to RGB888
picam2.configure("preview") # Configure camera for preview mode
picam2.start() # Start the camera
while True:
frame = picam2.capture_array() # Capture a frame from the camera
if frame is None:
print("Unable to read frame")
break
# Convert the captured frame from RGB to grayscale for face detection
gray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
# Detect faces in the grayscale image
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1, # Scale factor for face detection sensitivity
minNeighbors=5, # Minimum number of neighbor rectangles to retain a face detection
minSize=(30, 30) # Minimum size of detected faces
)
print("Found {0} faces!".format(len(faces))) # Print number of faces detected
# Draw rectangles around detected faces
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
# Display the frame with detected faces
cv2.imshow("Face Detection", frame)
# Press 'q' to exit the loop
if cv2.waitKey(1) & 0xFF == ord("q"):
break
# Stop the camera and close OpenCV windows
picam2.stop()
cv2.destroyAllWindows()
```
:::