{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.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":45867,"databundleVersionId":6924515,"sourceType":"competition"}],"dockerImageVersionId":30588,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import os\nimport cv2\nimport glob\nimport numpy as np\n\ndef generate_tiles(image_path, save_dir, tile_size, threshold_mean, threshold_std):\n    \"\"\"\n    Generates tiles from an image based on specified criteria and saves non-blank tiles to a directory.\n\n    Args:\n    - image_path (str): Path to the input image file.\n    - save_dir (str): Directory to save the generated tiles.\n    - tile_size (int): Size of each square tile (in pixels).\n    - threshold_mean (float): Minimum threshold for the mean pixel value to consider a tile non-blank.\n    - threshold_std (float): Minimum threshold for the standard deviation of pixel values to consider a tile non-blank.\n\n    Returns:\n    - None: Saves non-blank tiles to the specified directory.\n    \"\"\"\n\n    # Read the input image using OpenCV\n    img = cv2.imread(image_path)\n\n    # Extract image dimensions from the shape\n    height, width, _ = img.shape\n\n    # Calculate the number of tiles in rows and columns\n    rows = height // tile_size\n    cols = width // tile_size\n\n    # Create the directory to save tiles if it doesn't exist\n    os.makedirs(save_dir, exist_ok=True)\n\n    # Iterate through each tile in the image\n    for row in range(rows):\n        for col in range(cols):\n            x = col * tile_size\n            y = row * tile_size\n\n            # Extract the current tile from the image\n            tile = img[y:y+tile_size, x:x+tile_size]\n            tile_name = f\"{os.path.splitext(os.path.basename(image_path))[0]}_tile_{col}_{row}.png\"\n\n            # Convert the tile to a NumPy array for mean and std calculation\n            tile_np = np.array(tile)\n\n            # Check if the tile is not mostly blank based on mean and std thresholds\n            if tile_np.mean() >= threshold_mean and tile_np.std() >= threshold_std:\n                # Save the non-blank tile to the specified directory\n                tile_path = os.path.join(save_dir, tile_name)\n                cv2.imwrite(tile_path, tile)","metadata":{"execution":{"iopub.status.busy":"2023-11-24T15:46:36.039221Z","iopub.execute_input":"2023-11-24T15:46:36.039603Z","iopub.status.idle":"2023-11-24T15:46:36.049658Z","shell.execute_reply.started":"2023-11-24T15:46:36.039573Z","shell.execute_reply":"2023-11-24T15:46:36.048622Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Directory containing input images\nimage_dir = \"/kaggle/input/UBC-OCEAN/test_images/*.png\"\n\n# Directory to save the tiles\nsave_dir = \"/kaggle/working/output_tiles/\"\n\n# Get paths of all image files in the input directory\nimage_paths = glob.glob(image_dir)\n\n# Process each image to generate and save tiles\nfor image_path in image_paths:\n    # Generate tiles using specified parameters (adjustable)\n    generate_tiles(image_path, save_dir, tile_size=256,threshold_mean=170, threshold_std=15)","metadata":{"execution":{"iopub.status.busy":"2023-11-24T15:47:42.795859Z","iopub.execute_input":"2023-11-24T15:47:42.796587Z","iopub.status.idle":"2023-11-24T15:48:06.654552Z","shell.execute_reply.started":"2023-11-24T15:47:42.796555Z","shell.execute_reply":"2023-11-24T15:48:06.653731Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Acknowledgement:\nhttps://github.com/bnsreenu/python_for_microscopists","metadata":{}}]}