-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpredict.py
58 lines (40 loc) · 1.95 KB
/
predict.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import os
import ultralytics
from ultralytics import YOLO
import yaml
from PIL import Image
# Create an Ultralytics YOLOv8 model
model = ultralytics.YOLO('/home/sicily/bird-detector/yolov8s.pt')
# Folder containing images
image_folder = '/home/sicily/bird-detector/bird-detect3/bc_hanging_parrot_test'
# Output folder for saving prediction results
output_folder = 'output_results'
# Load experiment config
cfg = ultralytics.cfg.get_cfg(cfg='default.yaml')
# Create YOLO model and load the trained weights
model = YOLO(cfg.model)
model.load("/home/sicily/bird-detector/yolov8s.pt") # Replace with the path to your trained weights file
# Specify the folder containing unseen images
image_folder = '/home/sicily/bird-detector/bird-detect3/bc_hanging_parrot_test'
# List all image files in the folder
image_files = [f for f in os.listdir(image_folder) if f.endswith('.jpg') or f.endswith('.png')]
# Specify the output folder for saving prediction results
output_folder = 'prediction_results'
# Create the output folder if it doesn't exist
os.makedirs(output_folder, exist_ok=True)
# Process each unseen image
# Process each unseen image
for image_file in image_files:
image_path = os.path.join(image_folder, image_file)
# Open the unseen image using PIL
image = Image.open(image_path)
# Perform object detection on the image
results_pred = model(image)
# Save bounding box information for each image individually
with open(os.path.join(output_folder, f'{os.path.splitext(image_file)[0]}.txt'), 'w') as output_file:
for det in results_pred.pred[0]:
label, confidence, x1, y1, x2, y2 = det.tolist()
# Save bounding box information to the output file
output_file.write(f"{int(label)} {confidence} {x1} {y1} {x2} {y2}\n")
print(f"Saved prediction results for {image_file}")
# This script should correctly access and save the bounding box information for each detected object in the specified output folder.