From 252291cfe1a3062288981fa88abf6d7594a4d728 Mon Sep 17 00:00:00 2001 From: harshada Date: Wed, 14 Oct 2026 04:31:15 +0000 Subject: [PATCH] Upload files to "/" --- yolo26_8_tasks.py | 172 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 172 insertions(+) create mode 100644 yolo26_8_tasks.py diff --git a/yolo26_8_tasks.py b/yolo26_8_tasks.py new file mode 100644 index 0000000..d40bdc0 --- /dev/null +++ b/yolo26_8_tasks.py @@ -0,0 +1,172 @@ +""" +YOLO26 - 8 Computer Vision Tasks on a Single Image +---------------------------------------------------- +Image used for ALL tasks: ai_img.png (must be in the same folder as this script) + +Tasks: + 1. Detection + 2. Tracking (single image -> just detection + starting IDs, see note below) + 3. Segmentation + 4. Pose estimation -> SKIPPED here (no person in ai_img.png), code kept but commented out + 5. Classification (works, but see accuracy note below) + 6. ROI extraction (crops each detected box out of the image) + 7. Depth estimation (native YOLO26 task, yolo26n-depth.pt) + 8. OBB -> SKIPPED here (DOTA aerial classes don't match desk objects), commented out + +All results are saved into ./results/ + +Install: + pip install -U ultralytics +""" + +import os +import cv2 +import numpy as np +from ultralytics import YOLO + +IMAGE_PATH = "img.jpeg" +OUT_DIR = "results" +os.makedirs(OUT_DIR, exist_ok=True) + +# Model size: nano (n) misses small/awkward-angle objects (e.g. phones lying +# flat, scissors against clutter). Step up to "s" or "m" for better recall. +MODEL_SIZE = "s" # options: n, s, m, l, x +CONF = 0.15 # lower threshold catches faint/uncertain detections +IMG_SIZE = 1280 # higher resolution preserves small object detail + + +def save(result, name): + """Plot a YOLO result (boxes/masks/etc drawn on the image) and save it.""" + plotted = result.plot() + path = os.path.join(OUT_DIR, name) + cv2.imwrite(path, plotted) + print(f"Saved: {path}") + + +if __name__ == "__main__": + + if not os.path.exists(IMAGE_PATH): + raise FileNotFoundError(f"'{IMAGE_PATH}' not found in current folder.") + + # ========================================================== + # 1) DETECTION + # ========================================================== + det_result = None + try: + det_model = YOLO(f"yolo26{MODEL_SIZE}.pt") + det_result = det_model(IMAGE_PATH, conf=CONF, imgsz=IMG_SIZE, augment=True)[0] + save(det_result, "1_detection.png") + except Exception as e: + print(f"[1 - Detection] FAILED: {e}") + + # ========================================================== + # 2) TRACKING + # NOTE: tracking is built for video/frame sequences - it links + # object IDs across TIME using motion. On one static image there's + # nothing to track across frames, so this just runs detection and + # assigns each object a starting track ID (1, 2, 3...). It will run + # fine, but it isn't demonstrating real tracking behavior. + # ========================================================== + try: + track_model = YOLO(f"yolo26{MODEL_SIZE}.pt") + track_result = track_model.track(IMAGE_PATH, persist=True, conf=CONF, imgsz=IMG_SIZE)[0] + save(track_result, "2_tracking.png") + except Exception as e: + print(f"[2 - Tracking] FAILED: {e}") + + # ========================================================== + # 3) SEGMENTATION + # ========================================================== + try: + seg_model = YOLO(f"yolo26{MODEL_SIZE}-seg.pt") + seg_result = seg_model(IMAGE_PATH, conf=CONF, imgsz=IMG_SIZE)[0] + save(seg_result, "3_segmentation.png") + except Exception as e: + print(f"[3 - Segmentation] FAILED: {e}") + + # ========================================================== + # 4) POSE ESTIMATION - SKIPPED + # Pose models detect HUMAN keypoints (COCO-pose, 17 points/person). + # ai_img.png has no person in it, so this would return an empty + # result. Uncomment and point at a photo containing a person to use it. + # ========================================================== + # try: + # pose_model = YOLO("yolo26n-pose.pt") + # pose_result = pose_model(IMAGE_PATH)[0] + # save(pose_result, "4_pose.png") + # except Exception as e: + # print(f"[4 - Pose] FAILED: {e}") + + # ========================================================== + # 5) CLASSIFICATION + # NOTE: classification models expect ONE dominant subject per image + # (ImageNet-style). ai_img.png has many objects side by side, so the + # top-1 prediction is just whatever looks most salient to the model - + # treat it as a rough guess, not a scene description. + # ========================================================== + try: + cls_model = YOLO("yolo26n-cls.pt") + cls_result = cls_model(IMAGE_PATH)[0] + save(cls_result, "5_classification.png") + top5 = [(cls_result.names[i], round(float(p), 3)) + for i, p in zip(cls_result.probs.top5, cls_result.probs.top5conf)] + print(f"[5 - Classification] Top-5 guesses: {top5}") + except Exception as e: + print(f"[5 - Classification] FAILED: {e}") + + # ========================================================== + # 6) ROI EXTRACTION + # Not a separate YOLO model - "ROI" here means cropping each detected + # bounding box out of the original image and saving it as its own file. + # Reuses the detection result from Task 1. + # ========================================================== + try: + if det_result is not None: + orig = cv2.imread(IMAGE_PATH) + roi_dir = os.path.join(OUT_DIR, "6_roi_crops") + os.makedirs(roi_dir, exist_ok=True) + for i, box in enumerate(det_result.boxes): + x1, y1, x2, y2 = map(int, box.xyxy[0]) + crop = orig[max(y1, 0):y2, max(x1, 0):x2] + label = det_result.names[int(box.cls[0])] + cv2.imwrite(os.path.join(roi_dir, f"roi_{i}_{label}.png"), crop) + print(f"[6 - ROI] Saved {len(det_result.boxes)} crops to {roi_dir}") + else: + print("[6 - ROI] Skipped: no detection result available.") + except Exception as e: + print(f"[6 - ROI] FAILED: {e}") + + # ========================================================== + # 7) DEPTH ESTIMATION + # Native YOLO26 task - yolo26n-depth.pt outputs a per-pixel metric + # depth map (meters). No separate MiDaS/Depth-Anything model needed. + # ========================================================== + try: + depth_model = YOLO("yolo26n-depth.pt") + depth_result = depth_model(IMAGE_PATH, imgsz=768)[0] + + depth_map = depth_result.depth.data.cpu().numpy() # (H, W) float32, meters + np.save(os.path.join(OUT_DIR, "7_depth_raw.npy"), depth_map) + + depth_norm = cv2.normalize(depth_map, None, 0, 255, cv2.NORM_MINMAX).astype("uint8") + depth_color = cv2.applyColorMap(depth_norm, cv2.COLORMAP_MAGMA) + cv2.imwrite(os.path.join(OUT_DIR, "7_depth.png"), depth_color) + print(f"[7 - Depth] Saved depth map. Range: {depth_map.min():.2f}m - {depth_map.max():.2f}m") + except Exception as e: + print(f"[7 - Depth] FAILED: {e}") + + # ========================================================== + # 8) OBB - SKIPPED + # OBB models (yolo26n-obb.pt) are trained on DOTA (aerial/satellite + # imagery - planes, ships, vehicles, storage tanks, etc.). None of + # those classes exist in a desk photo, so this would return zero + # detections. Uncomment and point at an aerial/satellite image to use it. + # ========================================================== + # try: + # obb_model = YOLO("yolo26n-obb.pt") + # obb_result = obb_model(IMAGE_PATH)[0] + # save(obb_result, "8_obb.png") + # except Exception as e: + # print(f"[8 - OBB] FAILED: {e}") + + print("\nDone. Check the 'results' folder for all saved outputs.")