import json import os from dataclasses import dataclass import clip # Import OpenAI Model pip install git+https://github.com/openai/CLIP.git import cv2 import numpy as np import torch from tqdm import tqdm from PIL import Image as PIL_Image from ultralytics import YOLO 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 bounding_box: list[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, "bounding_box": [list(coords) for coords in obj.bounding_box], "segments": [list(seg) for seg in obj.segments], "clip_embedding": obj.clip_embedding.tolist(), "color_histogram": obj.color_histogram.tolist(), } 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, bounding_box=[(x1, y1, 0.0), (x2, y2, 0.0)], segments=[], clip_embedding=clip_embedding, color_histogram=np.ndarray(0) ) ) indices.append(i) h2, w2, _ = results[0].orig_img.shape 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 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__": scene_ids = [ "B6ByNegPMKs", # validation data "2t7WUuJeko7", "PX4nDJXEHrG", "q9vSo1VnCiC", "Vvot9Ly1tCj", "zsNo4HB9uLZ" ] for scene_id in tqdm(scene_ids): PATH = f"data/{scene_id}/matterport_color_images/{scene_id}/matterport_color_images/" findings = run_detection(PATH) write_json(findings, f"extracted_features/{scene_id}_features.json")