Files
MA_Param_Tuning/object_features_detector.py
T
2025-08-27 10:34:43 +02:00

176 lines
5.3 KiB
Python

import json
import os
from dataclasses import dataclass
from ultralytics import YOLO
import clip # Import OpenAI Model pip install git+https://github.com/openai/CLIP.git
import cv2
import torch
import numpy as np
from PIL import Image as PIL_Image
import time
device = "cuda" if torch.cuda.is_available() else "cpu"
yolo_model = YOLO('yolov9e-seg.pt')
clip_model, clip_preprocess = clip.load("ViT-B/32", device=device)
@dataclass
class DetectedObject:
class_name: str
top_corner: tuple
bottom_corner: tuple
segments: list[tuple]
clip_embedding: np.ndarray
color_histogram: np.ndarray
def detected_Object_to_dict(obj: DetectedObject):
return {
"class_name": obj.class_name,
"top_corner": list(obj.top_corner),
"bottom_corner": list(obj.bottom_corner),
"segments": [list(seg) for seg in obj.segments],
"clip_embedding": obj.clip_embedding.tolist(),
"color_histogram": obj.color_histogram.tolist(),
}
def dict_to_detected_object(d: dict):
return DetectedObject(
class_name=d["class_name"],
top_corner=tuple(d["top_corner"]),
bottom_corner=tuple(d["bottom_corner"]),
segments=[tuple(seg) for seg in d["segments"]],
clip_embedding=np.array(d["clip_embedding"]),
color_histogram=np.array(d["color_histogram"]),
)
def get_color_histogram(image_mask):
hsv_conversion = cv2.cvtColor(image_mask, cv2.COLOR_BGR2HSV)
mask_non_zero = (image_mask > 0).any(axis=2)
hues = hsv_conversion[:, :, 0][mask_non_zero]
if hues.size == 0:
return None
histogram = cv2.calcHist([hues], [0], None, [36], [0, 180])
return histogram
def object_and_feature_detection(image_path: str):
cv_image = cv2.imread(image_path)
results = yolo_model(cv_image)
masks = results[0].masks.data if results[0].masks is not None else None
if masks is None:
print("[ERROR] No masks found in the image.")
detected_objects = []
indices = []
for result in results:
for i, box in enumerate(result.boxes):
class_id = int(box.cls.item())
class_name = result.names[class_id]
confidence = box.conf.item()
if confidence > 0.6:
x1, y1, x2, y2 = box.xyxy[0][0].item(), box.xyxy[0][1].item(), box.xyxy[0][2].item(), box.xyxy[0][3].item()
print(f"Class: {class_name}, Confidence: {confidence}, Coordinates: ({x1, y1}, {x2, y2})")
cropped = cv_image[int(y1):int(y2), int(x1):int(x2)]
to_pil = PIL_Image.fromarray(cv2.cvtColor(cropped, cv2.COLOR_BGR2RGB))
processed_pil_image = clip_preprocess(to_pil).unsqueeze(0).to(device)
with torch.no_grad():
clip_embedding = clip_model.encode_image(processed_pil_image)
clip_embedding = clip_embedding / clip_embedding.norm(dim=-1, keepdim=True)
clip_embedding = clip_embedding.cpu().squeeze(0).numpy()
detected_objects.append(
DetectedObject(
class_name=class_name,
top_corner=(x1, y1),
bottom_corner=(x2, y2),
segments=[],
clip_embedding=clip_embedding,
color_histogram=np.ndarray(0)
)
)
indices.append(i)
h2, w2, _ = results[0].orig_img.shape
masks = None
lower_black = np.array([0, 0, 0])
upper_black = np.array([0, 0, 1])
n = 0
for i in indices:
mask = results[0].masks[i]
segment = []
for point in mask.xy[0]:
segment.append((int(point[0]), int(point[1])))
detected_objects[n].segments = segment
mask_raw = mask.cpu().data.numpy().transpose(1, 2, 0)
mask_3channel = cv2.cvtColor(mask_raw, cv2.COLOR_GRAY2BGR)
mask = cv2.resize(mask_3channel, (w2, h2))
mask = cv2.inRange(mask, lower_black, upper_black)
mask = cv2.bitwise_not(mask)
applied_mask = cv2.bitwise_and(results[0].orig_img, results[0].orig_img, mask=mask)
color_histogram = get_color_histogram(applied_mask)
detected_objects[n].color_histogram = color_histogram
n += 1
return detected_objects
def read_json(json_path: str):
with open(json_path, "r") as f:
raw = json.load(f)
data = [
{
"frame_id": entry["frame_id"],
"objects": [dict_to_detected_object(o) for o in entry["objects"]],
}
for entry in raw
]
return data
def run_detection(directory: str):
detected_objects = []
for filename in os.listdir(directory):
if filename.endswith(".jpg"):
detections = object_and_feature_detection(os.path.join(directory, filename))
detected_objects.append({
"frame_id": filename,
"objects": [detected_Object_to_dict(d) for d in detections]
})
return detected_objects
def write_json(content, file_name):
with open(file_name, "w") as f:
json.dump(content, f)
if __name__ == "__main__":
PATH = "17DRP5sb8fy/matterport_color_images/17DRP5sb8fy/_/matterport_color_images/"
findings = run_detection(PATH)
write_json(findings, "findings_test.json")