Bootstrap

yolov8 裁剪检测结果

1. 基础

本项目是在 Windows+YOLOV8环境配置 的基础上实现的
思路:将检测得到的物体边框提取,然后边框裁剪原图,并把裁剪后的结果保存在文件夹

2. 图片批量裁剪

2.1 检测裁剪

from ultralytics import YOLO
import cv2
import os

model = YOLO("yolov8n.pt")
names = model.names

# 获取文件夹中所有图像文件的路径
image_files = [os.path.join("./ultralytics/assets", f) for f in os.listdir("./ultralytics/assets") if f.endswith(".jpg") or f.endswith(".png")]
crop_dir_name = "ultralytics_crop"
if not os.path.exists(crop_dir_name):
    os.mkdir(crop_dir_name)

idx = 0

for image_file in image_files:
    # 读取图像
    im0 = cv2.imread(image_file)
    results = model.predict(im0, show=False)
    boxes = results[0].boxes.xyxy.cpu().tolist()
    clss = results[0].boxes.cls.cpu().tolist()
    annotated_frame = results[0].plot()

    if boxes is not None:
        for box, cls in zip(boxes, clss):
            idx += 1
            crop_obj = im0[int(box[1]):int(box[3]), int(box[0]):int(box[2])]
            cv2.imwrite(os.path.join(crop_dir_name, str(idx)+".png"), crop_obj)

    cv2.imshow("ultralytics", annotated_frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cv2.destroyAllWindows()

请添加图片描述

2.2 分割裁剪

from ultralytics import YOLO
import cv2
import os

model = YOLO("yolov8n-seg.pt")
names = model.names

# 获取文件夹中所有图像文件的路径
image_files = [os.path.join("./ultralytics/assets", f) for f in os.listdir("./ultralytics/assets") if f.endswith(".jpg") or f.endswith(".png")]
crop_dir_name = "ultralytics_crop"
if not os.path.exists(crop_dir_name):
    os.mkdir(crop_dir_name)

idx = 0

for image_file in image_files:
    # 读取图像
    im0 = cv2.imread(image_file)
    results = model.predict(im0, show=False)
    boxes = results[0].boxes.xyxy.cpu().tolist()
    clss = results[0].boxes.cls.cpu().tolist()
    annotated_frame = results[0].plot()

    if boxes is not None:
        for box, cls in zip(boxes, clss):
            idx += 1
            crop_obj = annotated_frame[int(box[1]):int(box[3]), int(box[0]):int(box[2])]
            cv2.imwrite(os.path.join(crop_dir_name, str(idx)+".png"), crop_obj)

    cv2.imshow("ultralytics", annotated_frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cv2.destroyAllWindows()

在这里插入图片描述

3. 视频裁剪

3.1 检测裁剪

from ultralytics import YOLO
import cv2
import os

model = YOLO("yolov8n.pt")
names = model.names

cap = cv2.VideoCapture("./ultralytics/assets/a2.mp4")
assert cap.isOpened(), "Error reading video file"

crop_dir_name = "ultralytics_crop"
if not os.path.exists(crop_dir_name):
    os.mkdir(crop_dir_name)

idx = 0
while cap.isOpened():
    success, im0 = cap.read()
    if not success:
        print("Video frame is empty or video processing has been successfully completed.")
        break

    results = model.predict(im0, show=False)
    boxes = results[0].boxes.xyxy.cpu().tolist()
    clss = results[0].boxes.cls.cpu().tolist()
    annotated_frame = results[0].plot()

    if boxes is not None:
        for box, cls in zip(boxes, clss):
            idx += 1
            crop_obj = im0[int(box[1]):int(box[3]), int(box[0]):int(box[2])]
            cv2.imwrite(os.path.join(crop_dir_name, str(idx)+".png"), crop_obj)

    cv2.imshow("ultralytics", annotated_frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

结果:
在这里插入图片描述

3.2 分割裁剪

from ultralytics import YOLO
import cv2
import os

model = YOLO("yolov8n-seg.pt")
names = model.names

cap = cv2.VideoCapture("./ultralytics/assets/a2.mp4")
assert cap.isOpened(), "Error reading video file"

crop_dir_name = "ultralytics_crop"
if not os.path.exists(crop_dir_name):
    os.mkdir(crop_dir_name)

idx = 0
while cap.isOpened():
    success, im0 = cap.read()
    if not success:
        print("Video frame is empty or video processing has been successfully completed.")
        break

    results = model.predict(im0, show=False)
    boxes = results[0].boxes.xyxy.cpu().tolist()
    clss = results[0].boxes.cls.cpu().tolist()
    annotated_frame = results[0].plot()

    if boxes is not None:
        for box, cls in zip(boxes, clss):
            idx += 1
            crop_obj = annotated_frame[int(box[1]):int(box[3]), int(box[0]):int(box[2])]
            cv2.imwrite(os.path.join(crop_dir_name, str(idx)+".png"), crop_obj)

    cv2.imshow("ultralytics", annotated_frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

结果:
请添加图片描述

3.3 实时裁剪

如果想打开摄像头实时裁剪只许把视频裁剪中的

cap = cv2.VideoCapture("./ultralytics/assets/a2.mp4")

改为

cap = cv2.VideoCapture(0)

即可

4. 源码

可以去 Windows+YOLOV8环境配置 下载源码,然后在主目录创建一个py文件,把上边代码贴进去运行即可

;