yolo_object.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import towhee
  2. import torch
  3. import cv2
  4. import numpy as np
  5. from PIL import Image, ImageOps
  6. yolo_model = torch.hub.load(r"C:\Users\Administrator\.cache\torch\hub\ultralytics_yolov5_master", 'custom', path="yolov5s.pt", source='local')
  7. # yolo_model = torch.hub.load("ultralytics/yolov5", "yolov5s")
  8. def yolo_detect(img):
  9. results = yolo_model(img)
  10. pred = results.pred[0][:, :4].cpu().numpy()
  11. boxes = pred.astype(np.int32)
  12. max_img = get_object(img, boxes)
  13. return max_img
  14. def get_object(img, boxes):
  15. if isinstance(img, str):
  16. img = Image.open(img)
  17. if len(boxes) == 0:
  18. return img
  19. max_area = 0
  20. # 选出最大的框
  21. x1, y1, x2, y2 = 0, 0, 0, 0
  22. for box in boxes:
  23. temp_x1, temp_y1, temp_x2, temp_y2 = box
  24. area = (temp_x2 - temp_x1) * (temp_y2 - temp_y1)
  25. if area > max_area:
  26. max_area = area
  27. x1, y1, x2, y2 = temp_x1, temp_y1, temp_x2, temp_y2
  28. max_img = img.crop((x1, y1, x2, y2))
  29. return max_img
  30. img = Image.open(r"D:\Code\ML\images\Mywork3\train_data\train\1\IMG_5024.JPG").convert("RGB")
  31. img = ImageOps.exif_transpose(img)
  32. results = yolo_model(img)
  33. results.show()
  34. # print(img)
  35. # result = yolo_detect(img)
  36. # result.show()
  37. dc = (
  38. towhee.glob['path'](r"D:\Code\ML\images\test02\test\prizm\26-1.jpg")
  39. .runas_op['path', "object"](yolo_detect)
  40. )
  41. print(dc)