import cv2
from ultralytics import YOLO

 

model = YOLO('yolov8x.pt')
webcam = cv2.VideoCapture(0)

blue_color = (255,0,0)

if not webcam.isOpened():
    print("Could not open webcam")
    exit()

while webcam.isOpened():
    status, frame = webcam.read()

    if status:
        results = model.predict(classes=0, device=0, conf=0.5, source=frame)

        for result in results:
            annotated_frame = result.plot(line_width=2, labels=False, boxes=False)
            boxes = result.boxes

            if boxes :
                for box in boxes :
                    x1 = int(box.xyxy[0,0])
                    y1 = int(box.xyxy[0,1])
                    x2 = int(box.xyxy[0,2])
                    y2 = int(box.xyxy[0,3])
                    cv2.rectangle(annotated_frame, (x1,y1), (x2,y2), blue_color, 3 )

                cv2.imshow("cam", annotated_frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

webcam.release()
cv2.destroyAllWindows()

     참조

      https://docs.ultralytics.com/modes/predict/#sources

 

        weights=ROOT / 'yolov5s.pt',  # model path or triton URL
        source=ROOT / 'data/images',  # file/dir/URL/glob/screen/0(webcam)
        data=ROOT / 'data/coco128.yaml',  # dataset.yaml path
        imgsz=(640, 640),  # inference size (height, width)
        conf_thres=0.25,  # confidence threshold
        iou_thres=0.45,  # NMS IOU threshold
        max_det=1000,  # maximum detections per image
        device='',  # cuda device, i.e. 0 or 0,1,2,3 or cpu
        view_img=False,  # show results
        save_txt=False,  # save results to *.txt
        save_conf=False,  # save confidences in --save-txt labels
        save_crop=False,  # save cropped prediction boxes
        nosave=False,  # do not save images/videos
        classes=None,  # filter by class: --class 0, or --class 0 2 3
        agnostic_nms=False,  # class-agnostic NMS
        augment=False,  # augmented inference
        visualize=False,  # visualize features
        update=False,  # update all models
        project=ROOT / 'runs/detect',  # save results to project/name
        name='exp',  # save results to project/name
        exist_ok=False,  # existing project/name ok, do not increment
        line_thickness=3,  # bounding box thickness (pixels)
        hide_labels=False,  # hide labels
        hide_conf=False,  # hide confidences
        half=False,  # use FP16 half-precision inference
        dnn=False,  # use OpenCV DNN for ONNX inference
        vid_stride=1,  # video frame-rate stride

 

results = model.predict(source=frame, show=True, device="0", hide_labels=True) # yolo 표시


from ultralytics import YOLO
import os
import cv2 as cv


model = YOLO("yolov8s.pt")

os.environ["OPENCV_FFMPEG_CAPTURE_OPTIONS"] = "rtsp_transport;udp"
cap = cv.VideoCapture('rtsp://210.99.70.120:1935/live/cctv001.stream')

while cap.isOpened():
ret, frame = cap.read()

if not ret:
print("Can't receive frame")
break

# cv.imshow('frame', frame) 영상표시
results = model.predict(source=frame, show=True, device="0") # yolo 표시

if cv.waitKey(1) == ord('q'):
break
cap.release()
cv.destroyAllWindows()

 

  1. Person
  2. Bicycle
  3. Car
  4. Motorcycle
  5. Airplane
  6. Bus
  7. Train
  8. Truck
  9. Boat
  10. Traffic light
  11. Fire hydrant
  12. Stop sign
  13. Parking meter
  14. Bench
  15. Bird
  16. Cat
  17. Dog
  18. Horse
  19. Sheep
  20. Cow
  21. Elephant
  22. Bear
  23. Zebra
  24. Giraffe
  25. Backpack
  26. Umbrella
  27. Handbag
  28. Tie
  29. Suitcase
  30. Frisbee
  31. Skis
  32. Snowboard
  33. Sports ball
  34. Kite
  35. Baseball bat
  36. Baseball glove
  37. Skateboard
  38. Surfboard
  39. Tennis racket
  40. Bottle
  41. Wine glass
  42. Cup
  43. Fork
  44. Knife
  45. Spoon
  46. Bowl
  47. Banana
  48. Apple
  49. Sandwich
  50. Orange
  51. Broccoli
  52. Carrot
  53. Hot dog
  54. Pizza
  55. Donut
  56. Cake
  57. Chair
  58. Couch
  59. Potted plant
  60. Bed
  61. Dining table
  62. Toilet
  63. TV
  64. Laptop
  65. Mouse
  66. Remote
  67. Keyboard
  68. Cell phone
  69. Microwave
  70. Oven
  71. Toaster
  72. Sink
  73. Refrigerator
  74. Book
  75. Clock
  76. Vase
  77. Scissors
  78. Teddy bear
  79. Hair drier
  80. Toothbrush

classes=0  하면 사람만 감지한다. 

yolo 모델을 변경합니다. "yolov8s.pt 

from ultralytics import YOLO

model = YOLO("yolov8s.pt")
results = model.predict(source="0", show=Truedevice="0" classes=0 )

 

 

참조 : https://learnopencv.com/train-yolov8-on-custom-dataset/

 

Train YOLOv8 on Custom Dataset – A Complete Tutorial

Train YOLOv8 on a custom pothole detection dataset. Training YOLOv8 Nano, Small, & Medium models and running inference for pothole detection on unseen videos.

learnopencv.com

 

파이참을 실행하고 터미널을 열고  학습 데이터를 다운받음 (25G 정도되니 시간이 많이 걸립니다.)

wget https://www.dropbox.com/s/qvglw8pqo16769f/pothole_dataset_v8.zip?dl=1 -O pothole_dataset_v8.zip

 

다운이 완료되면  ultralytics-main\datasets  폴더안에 이동후 해당 파일 이름으로 압축을 해제

 

train \images  

 

프로젝트에서 마우스 오른쪽 버튼을 누르고, New  -> File 

 

아래 이름으로 생성 

pothole_v8.yaml

 

 

 

 

 

아래 내용을 복사후 저장 

path: pothole_dataset_v8/
train: 'train/images'
val: 'valid/images'

# class names
names:
0: 'pothole'

 

훈련을 시킵니다. 

yolo task=detect mode=train model=yolov8n.pt imgsz=1280 data=pothole_v8.yaml epochs=50 batch=8 name=yolov8n_v8_50e

 

시간이.....

 

 

 

 

 

완료가 되면 runs\detect 폴더에 pt 파일이 생성됩니다. . 

 

 

 

 

프로젝트에 복사해주고 모델을 명을 변경해줍니다. 

from ultralytics import YOLO



model = YOLO("best.pt")
results = model.predict(source="0", show=True )

print(results)

 

스마트폰으로 포트홀 사진을 뛰운후 검출이 잘 됩니다. 

 

https://xandroid.tistory.com/entry/WebCam-%EC%9D%B4%EC%9A%A9%ED%95%9C-%EA%B0%9D%EC%B2%B4-%EC%9D%B8%EC%8B%9D

 

yolo8 & python 3.10 이용한 객체 인식 #1

1) 파이썬 설치 https://www.python.org/downloads/windows/ Python Releases for Windows The official home of the Python Programming Language www.python.org os 맞는 bit 다운로드후 설치 커스텀을 선택 IDLE는 체크를 안함, => 파이참을

xandroid.tistory.com

#1 이어서 

 

아무이름이나 지어주고 엔터 

아래 코드를 입력후

from ultralytics import YOLO

model = YOLO("yolov8s.pt")
results = model.predict(source="0", show=True)
print(results)

 

플레이 버튼을 누르면

 

아래와 같이 캠으로 객체인식이 가능

 

 

 

 

1) 파이썬 설치  

 

https://www.python.org/downloads/windows/  

 

Python Releases for Windows

The official home of the Python Programming Language

www.python.org

 

os 맞는 bit 다운로드후 설치 

 

커스텀을 선택  IDLE는 체크를 안함,  => 파이참을 이용

 

 

설치 경로를 기억 

 

 

인스톨 버튼을 누름

설치완료

 

 

2) 파이참 설치 ( IDE 툴 )

 

https://www.jetbrains.com/ko-kr/pycharm/

 

3) Yolo8 다운받기

 

https://github.com/ultralytics/ultralytics 

 

v8 이 더 빠르다고 ....

다운받은후 압축을 해제하고 적당한 폴더에 복사함

4) 파이참 실행 

해당경로를 아까 yolo8 다운 받은 경로로 변경

기존소스 선택 

 

터미널을 열고 

 

 

 

pip install ultralytics   엔터~~

Updating skeletons 완료될때까지 대기

 

 

 yolo predict model=yolov8n.pt source='https://ultralytics.com/images/bus.jpg'   

엔터

해당 경로에 객체 인식 결과 파일이   runs\detect\ 이미지 파일로 저장이됨  

 

 

+ Recent posts