計算機視覺 - 目標檢測
什麼是目標檢測?
目標檢測是一種計算機視覺技術,用於定點陣圖像或影片中物體的例項。
目標是識別物體的存在,並在其周圍繪製邊界框以指示其位置。目標檢測結合了影像分類和目標定位。
目標檢測的重要性
目標檢測對於各種現實世界的應用非常重要,例如:
- 自動駕駛汽車:檢測道路上的行人、車輛和障礙物。
- 監控:監控活動並識別可疑物體。
- 醫療保健:檢測醫學影像中的異常情況。
- 機器人技術:使機器人能夠與其環境中的物體互動。
目標檢測技術
目標檢測有多種技術,它們是:
- 傳統方法
- 基於機器學習的方法
- 基於深度學習的方法
傳統方法
傳統的目標檢測方法依賴於影像處理技術和定製的特徵。這些方法的準確性通常不如現代基於機器學習的方法,但更簡單、更快。
常用的傳統方法是Haar級聯。它使用級聯分類器,這些分類器透過正負影像訓練來檢測物體。
import cv2
# Load the pre-trained Haar Cascade classifier for face detection
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
# Read the input image
image = cv2.imread('image.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Detect faces
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
# Draw bounding boxes around detected faces
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), (255, 0, 0), 2)
cv2.imshow('Detected Faces', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
基於機器學習的方法
基於機器學習的方法使用從資料中學習以檢測物體的演算法。這些方法通常涉及對標記資料集進行分類器訓練。
最常用的基於機器學習的方法是方向梯度直方圖 (HOG) + SVM。這提取HOG特徵並使用支援向量機 (SVM) 對物體進行分類。
from skimage.feature import hog
from sklearn.svm import LinearSVC
import joblib
# Load the pre-trained HOG + SVM model
model = joblib.load('hog_svm_model.pkl')
# Extract HOG features from the input image
features, _ = hog(image, orientations=9, pixels_per_cell=(8, 8), cells_per_block=(2, 2), block_norm='L2-Hys', visualize=True)
# Predict the presence of objects using the trained SVM model
prediction = model.predict([features])
基於深度學習的方法
基於深度學習的方法憑藉其高精度和處理複雜影像的能力,徹底改變了目標檢測。這些方法使用卷積神經網路 (CNN) 來學習特徵並執行檢測。
常見的基於深度學習的方法如下所示:
- R-CNN(基於區域的卷積神經網路):提出候選區域並使用CNN對其進行分類。
- YOLO(你只需要看一次):將影像劃分為網格,並直接預測每個網格單元的邊界框和類別機率。
- SSD(單次多盒檢測器):類似於YOLO,但使用不同的架構來實現更快、更準確的檢測。
YOLO(你只需要看一次)
YOLO是一個流行且高效的目標檢測模型。它將影像劃分為網格,並預測每個網格單元的邊界框和類別機率。
您可以按照以下步驟使用YOLO:
- 步驟1:載入預訓練的YOLO模型。
import cv2
import numpy as np
# Load YOLO
net = cv2.dnn.readNet('yolov3.weights', 'yolov3.cfg')
layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
# Load the input image
image = cv2.imread('image.jpg')
height, width, channels = image.shape
# Prepare the image for YOLO
blob = cv2.dnn.blobFromImage(image, 0.00392, (416, 416), (0, 0, 0), True, crop=False)
net.setInput(blob)
# Run the model outs = net.forward(output_layers)
class_ids = []
confidences = []
boxes = []
for out in outs:
for detection in out:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence > 0.5:
# Object detected
center_x = int(detection[0] * width)
center_y = int(detection[1] * height)
w = int(detection[2] * width)
h = int(detection[3] * height)
# Rectangle coordinates
x = int(center_x - w / 2)
y = int(center_y - h / 2)
boxes.append([x, y, w, h])
confidences.append(float(confidence))
class_ids.append(class_id)
# Apply Non-Maximum Suppression
indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
# Draw bounding boxes
for i in range(len(boxes)):
if i in indexes:
x, y, w, h = boxes[i]
label = str(class_ids[i])
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.putText(image, label, (x, y + 30), cv2.FONT_HERSHEY_PLAIN, 3, (0, 255, 0), 3)
cv2.imshow('Object Detection', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
廣告