今天是第五天,前面幾天介紹lstm範例,今天可以寫一個簡單的yolo來分析多隻斑馬魚的行為,以下是程式碼
import cv2
import numpy as np
# 載入 YOLO 模型
def load_yolo_model():
net = cv2.dnn.readNet("yolov3.weights", "yolov3.cfg")
with open("coco.names", "r") as f:
classes = [line.strip() for line in f.readlines()]
layer_names = net.getLayerNames()
output_layers = [layer_names[i - 1] for i in net.getUnconnectedOutLayers()]
return net, classes, output_layers
# 偵測斑馬魚
def detect_fish(frame, net, output_layers):
height, width, channels = frame.shape
blob = cv2.dnn.blobFromImage(frame, 0.00392, (416, 416), (0, 0, 0), True, crop=False)
net.setInput(blob)
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 and class_id == 0: # 假設斑馬魚的類別ID是0
center_x = int(detection[0] * width)
center_y = int(detection[1] * height)
w = int(detection[2] * width)
h = int(detection[3] * height)
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)
indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
return boxes, confidences, indexes
# 繪製偵測結果
def draw_labels(boxes, confidences, indexes, frame):
font = cv2.FONT_HERSHEY_PLAIN
for i in range(len(boxes)):
if i in indexes:
x, y, w, h = boxes[i]
label = str(confidences[i])
color = (0, 255, 0)
cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)
cv2.putText(frame, label, (x, y - 10), font, 1, color, 1)
return frame
# 主程式
def main():
net, classes, output_layers = load_yolo_model()
cap = cv2.VideoCapture("zebrafish_video.mp4")
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
boxes, confidences, indexes = detect_fish(frame, net, output_layers)
frame = draw_labels(boxes, confidences, indexes, frame)
cv2.imshow("Zebrafish Detection", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
main()
載入 YOLO 模型 (load_yolo_model
函數):
yolov3.weights
) 和配置文件 (yolov3.cfg
)。coco.names
文件,將每個類別名稱儲存到 classes
列表中。偵測斑馬魚 (detect_fish
函數):
繪製偵測結果 (draw_labels
函數):
主函數 (main
函數):
zebrafish_video.mp4
) 並逐幀讀取。整個流程是:從影片中逐幀讀取影像,將影像輸入 YOLO 模型進行偵測,並將結果可視化顯示在影像上。這樣可以實時追蹤影片中的多隻斑馬魚。