|
|
import os |
|
|
import pandas as pd |
|
|
from ultralytics import YOLO |
|
|
|
|
|
def run_inference(model, image_path, conf_threshold, save_path): |
|
|
test_images = os.listdir(image_path) |
|
|
test_images.sort() |
|
|
|
|
|
bboxes = [] |
|
|
category_ids = [] |
|
|
test_images_names = [] |
|
|
|
|
|
|
|
|
for image_name in test_images: |
|
|
|
|
|
if not image_name.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp')): |
|
|
continue |
|
|
|
|
|
full_image_path = os.path.join(image_path, image_name) |
|
|
|
|
|
current_image_bboxes = [] |
|
|
current_image_category_ids = [] |
|
|
|
|
|
|
|
|
results = model(full_image_path) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
for pred in results[0].boxes: |
|
|
|
|
|
xmin, ymin, xmax, ymax = pred.xyxy[0].tolist() |
|
|
conf = pred.conf.item() |
|
|
class_id = int(pred.cls.item()) |
|
|
|
|
|
if conf >= conf_threshold: |
|
|
width = xmax - xmin |
|
|
height = ymax - ymin |
|
|
|
|
|
current_image_bboxes.append([xmin, ymin, width, height]) |
|
|
current_image_category_ids.append(class_id) |
|
|
|
|
|
test_images_names.append(image_name) |
|
|
bboxes.append(current_image_bboxes) |
|
|
category_ids.append(current_image_category_ids) |
|
|
|
|
|
|
|
|
df_predictions = pd.DataFrame(columns=["file_name", "bbox", "category_id"]) |
|
|
|
|
|
for i in range(len(test_images_names)): |
|
|
file_name = test_images_names[i] |
|
|
new_row = pd.DataFrame({"file_name": file_name, |
|
|
"bbox": str(bboxes[i]), |
|
|
"category_id": str(category_ids[i]), |
|
|
}, index=[0]) |
|
|
df_predictions = pd.concat([df_predictions, new_row], ignore_index=True) |
|
|
|
|
|
|
|
|
os.makedirs(os.path.dirname(save_path), exist_ok=True) |
|
|
df_predictions.to_csv(save_path, index=False) |
|
|
print(f"Inference results saved to: {save_path}") |
|
|
|
|
|
|
|
|
if __name__ == "__main__": |
|
|
|
|
|
|
|
|
current_directory = os.path.dirname(os.path.abspath(__file__)) |
|
|
TEST_IMAGE_PATH = "/tmp/data/test_images" |
|
|
SUBMISSION_SAVE_PATH = os.path.join(current_directory, "submission.csv") |
|
|
|
|
|
|
|
|
MODEL_WEIGHTS_PATH = os.path.join(current_directory, "best.pt") |
|
|
CONF_THRESHOLD = 0.30 |
|
|
|
|
|
|
|
|
model = YOLO(MODEL_WEIGHTS_PATH) |
|
|
|
|
|
|
|
|
run_inference(model, TEST_IMAGE_PATH, CONF_THRESHOLD, SUBMISSION_SAVE_PATH) |
|
|
|