一、使用yolov10模型檢測視頻中出現的行人,并保存為圖片,detect_person.py代碼如下:
from ultralytics import YOLOv10
import glob
import os
import cv2
import argparsedef detect_person(videoPath, savePath):if not os.path.exists(savePath):os.mkdir(savePath)# YOLOV10模型路徑modelpath = r'q:\yolov10-main\weights\yolov10m.pt'print("------------------",videoPath,savePath)model = YOLOv10(modelpath)timeF = 0image_count = 0# filenames = glob.glob(os.path.join(videoPath, '*.avi'))# 遍歷視頻文件夾for root, dirs, files in os.walk(videoPath):print("======",root)print("++++++",dirs)print("------",files,len(files))# 遍歷視頻文件for filename in files:# if(not filename.endswith(".avi")):# continueif(filename.split('.')[-1] not in ['avi','mp4']):continueimg = 1videofile = os.path.join(root, filename)video = cv2.VideoCapture(videofile)frames = int(video.get(cv2.CAP_PROP_FRAME_COUNT))# 遍歷視頻每一幀for _ in range(frames):ret, frame = video.read()timeF += 1if ret:results = model.predict(frame)[0]personcount = 0for box in results.boxes:if box.cls == 0 and box.conf > 0.5:personcount += 1# 圖片中出現大于2人,且間隔15幀,保存圖片if personcount >= 2 and timeF > 15 :cv2.imwrite(os.path.join(savePath, filename.split('\\')[-1][:-4] + '_' + str(img) + '.jpg'),frame)if image_count % 100 == 0:print("image_count : ",image_count)timeF = 0img += 1# 釋放資源video.release()# 刪除視頻源文件,不想刪除可以注釋掉os.remove(videofile)if __name__ == '__main__':parse = argparse.ArgumentParser(description='使用yolov10模型檢測視頻中出現的行人,并保存為圖片')parse.add_argument('--videoDir',required=True,help='視頻文件夾')parse.add_argument('--imageDir',required=True,help='保存圖片文件夾')args = parse.parse_args()detect_person(args.videoDir, args.imageDir)
二、在終端執行以上代碼的命令
python.exe detect_person.py --videoDir Q:\DATAS\adas-data\video-person\20250708 --imageDir Q:\DATAS\adas-data\video-person\images-20250718