자유게시판
테스트 파일 내용 설명 ( 본 테스트 파일은 인터넷에서 찾은 파일입니다. 참고용으로 사용하세요)
첨부된 파일은 YOLO 버젼8을 사용하여 웹캠이나 동양상 파일에서 사물을 탐지하기위한 파이썬 스크립트로
아래의 내용을 참고하시면 코드를 이해하시는데 도움이 되십니다.
import cv2
from ultralytics import YOLO
# Load the YOLOv8 model
model = YOLO('yolov8n.pt')
라이브러리 및 모델 로드:
cv2: 이미지와 비디오를 처리하는 OpenCV 라이브러리
ultralytics.YOLO: YOLO 모델을 사용할 수 있는 ultralytics 라이브러리
yolov8n.pt: 미리 훈련된 YOLOv8 모델의 가중치 파일
model = YOLO('yolov8n.pt'): 미리 훈련된 YOLOv8 모델을 로드
# 동영상 파일 사용시
# video_path = "path/to/your/video/file.mp4"
# cap = cv2.VideoCapture(video_path)
# webcam 사용시
cap = cv2.VideoCapture(0)
웹캠 사용 시: cap = cv2.VideoCapture(0): 웹캠을 캡처하기 위한 객체를 생성
동영상 파일 사용 시: 주석 처리된 부분을 해제하고, 동영상 파일 경로를 video_path 변수에 지정한 후 해당 파일을 캡처
비디오 프레임 처리 및 객체 탐지:
# Loop through the video frames
while cap.isOpened():
# Read a frame from the video
success, frame = cap.read()
if success:
# Run YOLOv8 inference on the frame
results = model(frame)
# Visualize the results on the frame
annotated_frame = results[0].plot()
cap.isOpened()로 캡처 객체가 열려있는지 확인
cap.read()를 통해 비디오에서 한 프레임을 Read
model(frame)을 통해 YOLOv8 모델을 사용하여 프레임에서 객체 탐지를 수행
results[0].plot()을 통해 탐지 결과를 시각화한 후 annotated_frame에 저장
결과 시각화 및 종료 조건:
# Display the annotated frame
cv2.imshow("YOLOv8 Inference", annotated_frame)
# Break the loop if 'q' is pressed
if cv2.waitKey(1) & 0xFF == ord("q"):
break
else:
# Break the loop if the end of the video is reached
break
cv2.imshow()로 시각화된 프레임을 표시
cv2.waitKey(1)로 사용자가 키보드 'q'를 누를 때까지 1ms마다 대기
사용자가 'q'를 누르면 반복문을 종료하고, 캡처 객체를 해제하고 창 Close
마무리:
# Release the video capture object and close the display window
cap.release()
cv2.destroyAllWindows()
비디오 캡처를 해제하고, 표시된 창 Close
'q'를 누르면 스크립트가 종료
로그인 후
참가 상태를 확인할 수 있습니다.