human_detect.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import cv2
  2. import numpy as np
  3. from ultralytics import YOLO
  4. def extract_clothing_area(image_path, output_path="output.jpg"):
  5. # 加载预训练的人体检测模型(YOLOv8)
  6. model = YOLO("/data/data/luosy/project/oral/models/yolov8n.pt") # 使用轻量级模型
  7. # 读取图像
  8. image = cv2.imread(image_path)
  9. if image is None:
  10. raise FileNotFoundError(f"Image not found at {image_path}")
  11. # 人体检测
  12. results = model.predict(image, classes=[0]) # classes=[0] 表示只检测人(COCO类别中0为"person")
  13. # 提取检测到的人体区域
  14. for result in results:
  15. boxes = result.boxes.xyxy.cpu().numpy() # 获取边界框坐标
  16. if len(boxes) == 0:
  17. print("未检测到人体")
  18. return
  19. # 选择第一个检测到的人体(假设图像中只有一人)
  20. x1, y1, x2, y2 = map(int, boxes[0])
  21. human_roi = image[y1:y2, x1:x2]
  22. # 简单方法:假设服装区域为人体上半部分(可调整)
  23. height = y2 - y1
  24. clothing_y1 = int(height * 0.1) # 顶部留空10%
  25. clothing_y2 = int(height * 0.6) # 上半部分(可根据需求调整)
  26. clothing_roi = human_roi[clothing_y1:clothing_y2, :]
  27. # 保存服装区域
  28. cv2.imwrite(output_path, clothing_roi)
  29. print(f"服装区域已保存至 {output_path}")
  30. if __name__ == "__main__":
  31. # 使用示例
  32. image_path1 = '/data/data/luosy/project/oral/data/key_frame/frame_013.jpg'
  33. image_path2 = '/data/data/luosy/project/oral/data/key_frame/frame_013_detect.jpg'
  34. extract_clothing_area(image_path1, image_path2)