YOLOv11.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. # Copyright (c) Opendatalab. All rights reserved.
  2. import time
  3. from collections import Counter
  4. from uuid import uuid4
  5. import numpy as np
  6. import torch
  7. from loguru import logger
  8. from ultralytics import YOLO
  9. language_dict = {
  10. "ch": "中文简体",
  11. "en": "英语",
  12. "japan": "日语",
  13. "korean": "韩语",
  14. "fr": "法语",
  15. "german": "德语",
  16. "ar": "阿拉伯语",
  17. "ru": "俄语"
  18. }
  19. def split_images(image, result_images=None):
  20. """
  21. 对输入文件夹内的图片进行处理,若图片竖向(y方向)分辨率超过400,则进行拆分,
  22. 每次平分图片,直至拆分出的图片竖向分辨率都满足400以下,将处理后的图片(拆分后的子图片)保存到输出文件夹。
  23. 避免保存因裁剪区域超出图片范围导致出现的无效黑色图片部分。
  24. """
  25. if result_images is None:
  26. result_images = []
  27. width, height = image.size
  28. long_side = max(width, height) # 获取较长边长度
  29. if long_side <= 400:
  30. result_images.append(image)
  31. return result_images
  32. new_long_side = long_side // 2
  33. sub_images = []
  34. if width >= height: # 如果宽度是较长边
  35. for x in range(0, width, new_long_side):
  36. # 判断裁剪区域是否超出图片范围,如果超出则不进行裁剪保存操作
  37. if x + new_long_side > width:
  38. continue
  39. box = (x, 0, x + new_long_side, height)
  40. sub_image = image.crop(box)
  41. sub_images.append(sub_image)
  42. else: # 如果高度是较长边
  43. for y in range(0, height, new_long_side):
  44. # 判断裁剪区域是否超出图片范围,如果超出则不进行裁剪保存操作
  45. if y + new_long_side > height:
  46. continue
  47. box = (0, y, width, y + new_long_side)
  48. sub_image = image.crop(box)
  49. sub_images.append(sub_image)
  50. for sub_image in sub_images:
  51. split_images(sub_image, result_images)
  52. return result_images
  53. def resize_images_to_224(image):
  54. """
  55. 若分辨率小于224则用黑色背景补齐到224*224大小,若大于等于224则调整为224*224大小。
  56. Works directly with NumPy arrays.
  57. """
  58. try:
  59. # Handle numpy array directly
  60. if len(image.shape) == 3: # Color image
  61. height, width, channels = image.shape
  62. else: # Grayscale image
  63. height, width = image.shape
  64. image = np.stack([image] * 3, axis=2) # Convert to RGB
  65. if width < 224 or height < 224:
  66. # Create black background
  67. new_image = np.zeros((224, 224, 3), dtype=np.uint8)
  68. # Calculate paste position
  69. paste_x = (224 - width) // 2
  70. paste_y = (224 - height) // 2
  71. # Paste original image onto black background
  72. new_image[paste_y:paste_y + height, paste_x:paste_x + width] = image
  73. image = new_image
  74. else:
  75. # Resize using cv2 functionality or numpy interpolation
  76. # Method 1: Using cv2 (preferred for better quality)
  77. import cv2
  78. image = cv2.resize(image, (224, 224), interpolation=cv2.INTER_LANCZOS4)
  79. return image
  80. except Exception as e:
  81. logger.exception(e)
  82. class YOLOv11LangDetModel(object):
  83. def __init__(self, langdetect_model_weight, device):
  84. self.model = YOLO(langdetect_model_weight)
  85. if str(device).startswith("npu"):
  86. self.device = torch.device(device)
  87. else:
  88. self.device = device
  89. def do_detect(self, images: list):
  90. all_images = []
  91. for image in images:
  92. height, width = image.shape[:2]
  93. if width < 100 and height < 100:
  94. continue
  95. temp_images = split_images(image)
  96. for temp_image in temp_images:
  97. all_images.append(resize_images_to_224(temp_image))
  98. # langdetect_start = time.time()
  99. images_lang_res = self.batch_predict(all_images, batch_size=256)
  100. # logger.info(f"image number of langdetect: {len(images_lang_res)}, langdetect time: {round(time.time() - langdetect_start, 2)}")
  101. if len(images_lang_res) > 0:
  102. count_dict = Counter(images_lang_res)
  103. language = max(count_dict, key=count_dict.get)
  104. else:
  105. language = None
  106. return language
  107. def predict(self, image):
  108. results = self.model.predict(image, verbose=False, device=self.device)
  109. predicted_class_id = int(results[0].probs.top1)
  110. predicted_class_name = self.model.names[predicted_class_id]
  111. return predicted_class_name
  112. def batch_predict(self, images: list, batch_size: int) -> list:
  113. images_lang_res = []
  114. for index in range(0, len(images), batch_size):
  115. lang_res = [
  116. image_res.cpu()
  117. for image_res in self.model.predict(
  118. images[index: index + batch_size],
  119. verbose = False,
  120. device=self.device,
  121. )
  122. ]
  123. for res in lang_res:
  124. predicted_class_id = int(res.probs.top1)
  125. predicted_class_name = self.model.names[predicted_class_id]
  126. images_lang_res.append(predicted_class_name)
  127. return images_lang_res