{"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"},{"sourceId":297798014,"sourceType":"kernelVersion"}],"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":"# **Extracting Square Patches of Jaguar Pattern**","metadata":{}},{"cell_type":"code","source":"import os\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n!mkdir test","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-10T02:36:12.308334Z","iopub.execute_input":"2026-02-10T02:36:12.309388Z","iopub.status.idle":"2026-02-10T02:36:42.183462Z","shell.execute_reply.started":"2026-02-10T02:36:12.309348Z","shell.execute_reply":"2026-02-10T02:36:42.182564Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"paths=[]\nfor dirname, _, filenames in os.walk('/kaggle/input/notebooks/stpeteishii/jaguar-dataset-background-removal/test'):\n    for filename in filenames:\n        paths+=[(os.path.join(dirname, filename))]\nprint(len(paths))","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport cv2\n\ndef make_patch(path):\n    # Load image\n    img = cv2.imread(path)\n    if img is None:\n        return\n    \n    file_name = path.split('/')[-1]\n    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n    \n    H, W = gray.shape\n    PATCH_SIZE = 256   \n    STRIDE = 16\n    KERNEL_SIZE = 5  # Check for 5x5 black blocks\n    \n    best_score = -1\n    best_patch = None\n    \n    # Iterate through the image with a stride\n    for y in range(0, H - PATCH_SIZE, STRIDE):\n        for x in range(0, W - PATCH_SIZE, STRIDE):\n            patch_gray = gray[y:y+PATCH_SIZE, x:x+PATCH_SIZE]\n            \n            # --- Logic to exclude black background ---\n            # Use boxFilter to sum up pixel values in a 5x5 window.\n            # normalize=False gives us the raw sum of pixels in the 5x5 area.\n            check_map = cv2.boxFilter(patch_gray, -1, (KERNEL_SIZE, KERNEL_SIZE), normalize=False)\n            \n            # If any 5x5 area has a sum of 0, it means a pure black block exists.\n            # We skip this patch to avoid background contamination.\n            if np.any(check_map == 0):\n                continue\n            # ------------------------------------------\n\n            # Calculate Variance of Laplacian as a focus/texture score\n            score = cv2.Laplacian(patch_gray, cv2.CV_64F).var()\n            \n            if score > best_score:\n                best_score = score\n                best_patch = img[y:y+PATCH_SIZE, x:x+PATCH_SIZE]\n                \n    # Save the best patch found\n    if best_patch is not None:\n        cv2.imwrite(f\"/kaggle/working/test/{file_name}\", best_patch)        \n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-10T02:38:50.130998Z","iopub.execute_input":"2026-02-10T02:38:50.131346Z","iopub.status.idle":"2026-02-10T02:38:50.140353Z","shell.execute_reply.started":"2026-02-10T02:38:50.131314Z","shell.execute_reply":"2026-02-10T02:38:50.139217Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for path in paths:\n    make_patch(path)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-10T02:38:52.482005Z","iopub.execute_input":"2026-02-10T02:38:52.482352Z","iopub.status.idle":"2026-02-10T02:38:53.136504Z","shell.execute_reply.started":"2026-02-10T02:38:52.482323Z","shell.execute_reply":"2026-02-10T02:38:53.135509Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"paths_patch=[]\nfor dirname, _, filenames in os.walk('/kaggle/working/test'):\n    for filename in filenames:\n        paths_patch+=[(os.path.join(dirname, filename))]\nprint(len(paths_patch))","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from PIL import Image\nfor path in paths_patch[0:10]:\n    img = plt.imread(path)\n    plt.imshow(img)\n    plt.show()","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}