Image2YoyoImage.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import towhee
  2. import torch
  3. import os
  4. import glob
  5. from PIL import Image, ImageOps
  6. from MyModel import MyModel
  7. import numpy as np
  8. vec_num = 0
  9. yolo_model = torch.hub.load(r"C:\Users\Administrator\.cache\torch\hub\ultralytics_yolov5_master", 'custom',
  10. path="yolov5s.pt", source='local')
  11. dataset_path = [r"D:\Code\ML\images\test02\test(mosaic,pz)\*\*\*\*"]
  12. yolo_dataset_dir = r"D:\Code\ML\images\test02\test(mosaic,pz)_yolo"
  13. def get_save_dir(save_dir, source_path):
  14. path02, path01 = os.path.split(source_path)
  15. path03, path02 = os.path.split(path02)
  16. path04, path03 = os.path.split(path03)
  17. path05, path04 = os.path.split(path04)
  18. return os.path.join(save_dir, path04, path03, path02, path01)
  19. def yolo_detect(img_path):
  20. dest_path = get_save_dir(yolo_dataset_dir, img_path)
  21. save_dir = os.path.split(dest_path)[0]
  22. # 如果已经存在这个yolo检测后的图片
  23. if os.path.exists(dest_path):
  24. print("----已经存在 ", dest_path)
  25. return
  26. img = Image.open(img_path)
  27. img = ImageOps.exif_transpose(img)
  28. results = yolo_model(img)
  29. pred = results.pred[0][:, :4].cpu().numpy()
  30. boxes = pred.astype(np.int32)
  31. max_img = get_object(img_path, boxes)
  32. if not os.path.exists(save_dir):
  33. os.makedirs(save_dir)
  34. max_img.save(dest_path)
  35. print(dest_path)
  36. def get_object(img, boxes):
  37. if isinstance(img, str):
  38. img = Image.open(img)
  39. if len(boxes) == 0:
  40. return img
  41. max_area = 0
  42. # 选出最大的框
  43. x1, y1, x2, y2 = 0, 0, 0, 0
  44. for box in boxes:
  45. temp_x1, temp_y1, temp_x2, temp_y2 = box
  46. area = (temp_x2 - temp_x1) * (temp_y2 - temp_y1)
  47. if area > max_area:
  48. max_area = area
  49. x1, y1, x2, y2 = temp_x1, temp_y1, temp_x2, temp_y2
  50. max_img = img.crop((x1, y1, x2, y2))
  51. return max_img
  52. data = (towhee.glob['path'](*dataset_path)
  53. .runas_op['path', ''](yolo_detect)
  54. )
  55. print('end')