{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.12.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":126777,"databundleVersionId":15314950,"sourceType":"competition"}],"dockerImageVersionId":31259,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# **Jaguar Dataset Background Removal**\n\n**Physically removes background from images using alpha channel.**","metadata":{}},{"cell_type":"code","source":"import cv2\nimport matplotlib.pyplot as plt\nimport os\n\ndef demonstrate_alpha_issue(image_path):\n    \"\"\"\n    Shows the difference between a standard load and an alpha-aware load.\n    \"\"\"\n    # 1. Standard Load: Ignores the alpha channel, making hidden bushes visible.\n    img_standard = cv2.imread(str(image_path))\n    if img_standard is None:\n        print(\"File not found.\")\n        return\n    img_standard = cv2.cvtColor(img_standard, cv2.COLOR_BGR2RGB)\n\n    # 2. Alpha-Aware Load: Uses the 4th channel to physically remove the background.\n    img_alpha = cv2.imread(str(image_path), cv2.IMREAD_UNCHANGED)\n    \n    if img_alpha.shape[2] == 4:\n        b, g, r, a = cv2.split(img_alpha)\n        # Create an RGB image and set pixels to 0 (black) where alpha is 0\n        img_masked = cv2.merge([r, g, b]) # RGB for display\n        img_masked[a == 0] = 0\n    else:\n        print(\"This image does not have an alpha channel.\")\n        return\n\n    # Comparison Display\n    fig, ax = plt.subplots(1, 2, figsize=(12, 5))\n    ax[0].imshow(img_standard)\n    ax[0].set_title(\"Standard Load (Ignores Alpha)\\n-> Hidden Bushes Appear\")\n    \n    ax[1].imshow(img_masked)\n    ax[1].set_title(\"Masked Load (Uses Alpha)\\n-> Background Truly Removed\")\n    \n    plt.tight_layout()\n    plt.show()\n\n# Example:\n# demonstrate_alpha_issue(\"path/to/your_image.png\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-15T05:52:35.322157Z","iopub.execute_input":"2026-02-15T05:52:35.322565Z","iopub.status.idle":"2026-02-15T05:52:35.706472Z","shell.execute_reply.started":"2026-02-15T05:52:35.322538Z","shell.execute_reply":"2026-02-15T05:52:35.705736Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"demonstrate_alpha_issue(\"/kaggle/input/jaguar-re-id/train/train/train_0001.png\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-15T05:52:35.708950Z","iopub.execute_input":"2026-02-15T05:52:35.709574Z","iopub.status.idle":"2026-02-15T05:52:37.080134Z","shell.execute_reply.started":"2026-02-15T05:52:35.709535Z","shell.execute_reply":"2026-02-15T05:52:37.079185Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import cv2\nimport os\nfrom pathlib import Path\nfrom tqdm import tqdm\n\ndef sanitize_dataset(input_root, output_root, bg_color=0):\n    \"\"\"\n    Physically removes background from images using alpha channel.\n    input_root: Path to original dataset (containing train/test)\n    output_root: Path where cleaned dataset will be saved\n    bg_color: Color of the removed background (0 for black, 255 for white)\n    \"\"\"\n    input_root = Path(input_root)\n    output_root = Path(output_root)\n\n    # Supported image extensions\n    extensions = [\".png\", \".jpg\", \".jpeg\", \".bmp\"]\n\n    # Gather all image files\n    image_paths = [p for p in input_root.rglob('*') if p.suffix.lower() in extensions]\n    \n    print(f\"Found {len(image_paths)} images. Starting sanitization...\")\n\n    for img_path in tqdm(image_paths):\n        # 1. Load with alpha channel\n        img = cv2.imread(str(img_path), cv2.IMREAD_UNCHANGED)\n        \n        if img is None:\n            continue\n\n        # 2. Process background if alpha exists\n        if img.shape[2] == 4:\n            b, g, r, a = cv2.split(img)\n            # Mask where alpha is 0 (transparent)\n            mask = (a == 0)\n            \n            # Create RGB image and fill background\n            clean_img = cv2.merge([b, g, r])\n            clean_img[mask] = bg_color\n        else:\n            # If no alpha channel, just copy (or skip if you only want masked ones)\n            clean_img = img\n\n        # 3. Maintain directory structure\n        relative_path = img_path.relative_to(input_root)\n        save_path = output_root / relative_path\n        save_path.parent.mkdir(parents=True, exist_ok=True)\n\n        # 4. Save the result (Saving as PNG to keep it lossless)\n        cv2.imwrite(str(save_path), clean_img)\n\n# --- Usage ---\n# sanitize_dataset(\"path/to/original_dataset\", \"path/to/cleaned_dataset\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-15T05:52:37.093827Z","iopub.status.idle":"2026-02-15T05:52:37.094276Z","shell.execute_reply.started":"2026-02-15T05:52:37.094047Z","shell.execute_reply":"2026-02-15T05:52:37.094074Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_path='/kaggle/input/jaguar-re-id/train/train'\ntest_path='/kaggle/input/jaguar-re-id/test/test'\ncleaned_train_path='/kaggle/working/train'\ncleaned_test_path='/kaggle/working/test'","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-15T05:52:37.095214Z","iopub.status.idle":"2026-02-15T05:52:37.095620Z","shell.execute_reply.started":"2026-02-15T05:52:37.095401Z","shell.execute_reply":"2026-02-15T05:52:37.095462Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sanitize_dataset(train_path, cleaned_train_path)\nsanitize_dataset(test_path, cleaned_test_path)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-15T05:52:37.096770Z","iopub.status.idle":"2026-02-15T05:52:37.097132Z","shell.execute_reply.started":"2026-02-15T05:52:37.096952Z","shell.execute_reply":"2026-02-15T05:52:37.096978Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}