seg.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. from ultralytics import YOLO
  2. import cv2
  3. import numpy as np
  4. # Load an official or custom model
  5. model = YOLO('yolov8s-seg.pt') # Load an official Segment model
  6. # Open the input video
  7. cap = cv2.VideoCapture(0)
  8. if not cap.isOpened():
  9. raise Exception("Error: Could not open video.")
  10. while cap.isOpened():
  11. # Read a frame from the input video
  12. success, frame = cap.read()
  13. if success:
  14. # Run YOLOv8 tracking on the frame, persisting tracks between frames
  15. results = model.track(frame, iou=0.65, conf=0.40, persist=True, imgsz=640, verbose=False, tracker="botsort.yaml")
  16. # Process results list
  17. for result in results:
  18. if result.boxes.id != None: # this will ensure that id is not None -> exist tracks
  19. boxes = result.boxes.xyxy.cpu().numpy().astype(int)
  20. masks = result.masks.data.cpu().numpy().astype(int)
  21. ids = result.boxes.id.cpu().numpy().astype(int)
  22. classes = result.boxes.cls.cpu().numpy()
  23. class_names = result.names
  24. for box, mask, id, class_id in zip(boxes, masks, ids, classes):
  25. color = (0, 0, 255)
  26. # Mask
  27. color_mask = np.zeros_like(frame)
  28. mask = cv2.resize(mask, (frame.shape[1], frame.shape[0]), interpolation=cv2.INTER_NEAREST)
  29. color_mask[mask > 0] = color
  30. alpha = 0.3
  31. frame = cv2.addWeighted(frame, 1, color_mask, alpha, 0)
  32. # Mask Boder
  33. mask_contours, _ = cv2.findContours(mask.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  34. frame = cv2.drawContours(frame, mask_contours, -1, color, 2)
  35. # Text
  36. class_name = class_names[class_id]
  37. text = f"{class_name}"
  38. font = cv2.FONT_HERSHEY_SIMPLEX
  39. fontScale = 1.2
  40. fontColor = (0, 0, 255)
  41. thickness = 3
  42. textSize = cv2.getTextSize(text, font, fontScale, thickness)[0]
  43. textWidth, textHeight = textSize[0], textSize[1]
  44. centerX = (box[0]+box[2])//2 - textWidth // 2
  45. centerY = (box[1]+box[3])//2 + textHeight // 2
  46. frame = cv2.putText(
  47. frame,
  48. text,
  49. (centerX, centerY),
  50. font,
  51. fontScale,
  52. fontColor,
  53. thickness
  54. )
  55. cv2.imshow("YOLOv8 Segmentation", frame)
  56. # Check for the 'q' key to exit
  57. if cv2.waitKey(10) & 0xFF == ord('q'):
  58. break
  59. else:
  60. break
  61. # Release the input video capture and output video writerй
  62. cap.release()
  63. # Close all OpenCV windows
  64. cv2.destroyAllWindows()