기본 webcam detect code
- model적용 및 FPS 측정
import datetime
import cv2
from ultralytics import YOLO
# 웹캠 연결
cap = cv2.VideoCapture(0)
#### YOLO 모델 생성
model = YOLO("models/yolov8n.pt")
while cap.isOpened():
start = datetime.datetime.now()
# 한 frame(이미지)을 읽기
succ, frame = cap.read()
if not succ:
print("웹캠 연결에 문제가 생겼습니다.")
break
# flip(대칭)
frame = cv2.flip(frame, 1) # 양수: 좌우, 0: 상하, 음수: 상하좌우
###############################################
# YOLO 모델을 이용한 추론 -> 결과 이미지 생성
###############################################
img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # yolo는 rgb 이미지를 학습시킨다.
# 추론. 추론대상이미지타입 - 문자열(경로), Image(ndarray, PIL.Image)
result = model(img,
conf=0.5, # 확률이 0.5 이상인 것만 결과로 리턴
verbose=False)[0] # 추론 결과 로그를 출력하지 않는다.
# 결과에서 위치, 클래스 정보 추출
### (찾은 object 개수, shape)
xyxy_list = result.boxes.xyxy.to("cpu").numpy().astype("int32")
cls_list = result.boxes.cls.to("cpu").numpy().astype("int32")
conf_list = result.boxes.conf.to("cpu").numpy()
# for in 문을 이용해 찾은 object 별로 bbox 처리를 한다.
for xyxy, cls, conf in zip(xyxy_list, cls_list, conf_list):
pt1, pt2 = xyxy[:2], xyxy[2:]
txt = f"{result.names[cls]} - {conf*100:.3f}%"
# box
cv2.rectangle(frame, pt1, pt2, color=(255, 0, 0), thickness=2)
cv2.putText(frame, txt, org=pt1, fontFace=cv2.FONT_HERSHEY_COMPLEX, fontScale=1, color=(200,0,0), thickness=1, lineType=cv2.LINE_AA)
end = datetime.datetime.now()
total = (end - start).total_seconds()
print(f'Time to process 1 frame: {total * 1000:.0f} milliseconds')
fps = f'FPS: {1 / total:.2f}'
cv2.putText(frame, fps, (10, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
# 영상 출력
cv2.imshow("frame", frame)
# 중단여부확인
if cv2.waitKey(1) == 27: # ESC를 입력하면
break
# 마무리
cap.release() # 웹캠연결 종료
cv2.destroyAllWindows() # 출력 윈도우 종료
tracking code
- bytetrack.yaml 파일 이용
# Ultralytics YOLO 🚀, AGPL-3.0 license
# Default YOLO tracker settings for ByteTrack tracker https://github.com/ifzhang/ByteTrack
tracker_type: bytetrack # tracker type, ['botsort', 'bytetrack']
track_high_thresh: 0.5 # threshold for the first association
track_low_thresh: 0.1 # threshold for the second association
new_track_thresh: 0.6 # threshold for init new track if the detection does not match any tracks
track_buffer: 30 # buffer to calculate the time when to remove tracks
match_thresh: 0.8 # threshold for matching tracks
# min_box_area: 10 # threshold for min box areas(for tracker evaluation, not used for now)
# mot20: False # for tracker evaluation(not used for now)
bytetrack.yaml 파일에 위와 같은 내용이 있으면 된다
- 파라미터들에 대한 내용 학습 필요
- 기본 tracking code
from ultralytics import YOLO
# Load the model and run the tracker with a custom configuration file
model = YOLO('yolov8n.pt')
results = model.track(source="DownloadVideo/Inside the locker room following Damian Lillards game winner dametime fearthedeer nba bucks.mp4", tracker='bytetrack.yaml', show=True)
로컬 GPU로 돌리기 참고
https://kenkyuanime.com/vscode%EB%A1%9Cgpu%EC%82%AC%EC%9A%A9/
'프로젝트 > Data_Analysis_Track_33_FinalProject' 카테고리의 다른 글
| FinalProject_10(개별 Action 수행, webcam detect + tracking기능 구현) (0) | 2024.01.25 |
|---|---|
| FinalProject_09(개별 Action 수행, 파이썬 웹 연동) (1) | 2024.01.22 |
| FinalProject_07(개별 Action 수행, AWS 학습) (0) | 2024.01.16 |
| FinalProject_06(개별 Action 수행, sequential img inference) (0) | 2024.01.12 |
| FinalProject_05(개별 Action 수행, Modeling) (2) | 2024.01.11 |