я новичок в yolo show и впервые пишу это в блокноте Google Colab: >
Код: Выделить всё
from google.colab import drive
drive.mount('/content/drive')
!pip install torch torchvision opencv-python
!pip install ultralytics --quiet
import torch
torch.cuda.is_available()
import cv2
import numpy as np
import os
from google.colab.patches import cv2_imshow
from ultralytics import YOLO
# Load your model
model_path = '/content/drive/MyDrive/Data/runs/detect/train7/weights/best.pt' # Update with the correct path to your model
model = YOLO(model_path)
# Root directory containing subdirectories of images
root_dir = '/content/drive/My Drive/content/drive/MyDrive/Data/out_test' # Update with the correct path to your root directory
# Directory to save cropped images
save_dir = '/content/drive/My Drive/cropped_images'
os.makedirs(save_dir, exist_ok=True)
def crop_objects(img, results, save_dir, img_name):
# Get the bounding boxes
boxes = results[0].boxes.xyxy.cpu().numpy() # Extracting bounding boxes from results
cropped_images = []
for i, box in enumerate(boxes):
x1, y1, x2, y2 = map(int, box[:4])
# Crop the image
cropped_img = img[y1:y2, x1:x2]
cropped_images.append(cropped_img)
# Save the cropped image
output_path = os.path.join(save_dir, f'{img_name}_cropped_{i}.jpg')
cv2.imwrite(output_path, cropped_img)
print(f'Cropped image saved to {output_path}')
return cropped_images
# Walk through all subdirectories and process images
for subdir, dirs, files in os.walk(root_dir):
for file in files:
img_path = os.path.join(subdir, file)
if img_path.lower().endswith(('png', 'jpg', 'jpeg')):
print(f"Processing image: {img_path}")
img = cv2.imread(img_path)
if img is None:
print(f"Could not read image: {img_path}")
continue
img_name = os.path.splitext(file)[0]
results = model(img) # Run inference on the image
# Debugging: Check results
print(f"Results for {img_path}: {results}")
crop_objects(img, results, save_dir, img_name)
Как она работает, но нет ошибок, но у меня нет обрезанных изображений? что я могу сделать, чтобы исправить этот код?
Мой результат — обрезанные изображения в папке.
Подробнее здесь: https://stackoverflow.com/questions/786 ... -of-yolov8