Team Ai
Datasetpublic

codeShare/lora-training-data

sourceHugging Faceupdated 1mo agoView on Hugging Face
2likes785downloads
split_images_horizontallyipynb.ipynb150 linesDownload Raw Back to root
1{2  "nbformat": 4,3  "nbformat_minor": 0,4  "metadata": {5    "colab": {6      "provenance": []7    },8    "kernelspec": {9      "name": "python3",10      "display_name": "Python 3"11    },12    "language_info": {13      "name": "python"14    }15  },16  "cells": [17    {18      "cell_type": "code",19      "execution_count": null,20      "metadata": {21        "id": "72K9kxwbp7Iw"22      },23      "outputs": [],24      "source": []25    },26    {27      "cell_type": "code",28      "metadata": {29        "id": "d5813f52"30      },31      "source": [32        "from PIL import Image\n",33        "import zipfile\n",34        "import os\n",35        "import shutil\n",36        "from google.colab import drive\n",37        "\n",38        "# Mount Google Drive (if not already mounted)\n",39        "drive.mount('/content/drive', force_remount=True)\n",40        "\n",41        "# @markdown --- Input Settings ---\n",42        "input_zip_path = '/content/drive/MyDrive/frames_v3_kf.zip' # @param {type:\"string\"}\n",43        "# @markdown --- Output Settings ---\n",44        "output_base_name = 'split_images3' # @param {type:\"string\"}\n",45        "# @markdown This will create three zip files: `split_images_left.zip`, `split_images_middle.zip`, `split_images_right.zip`\n",46        "\n",47        "dest_folder = '/content/drive/MyDrive/'\n",48        "\n",49        "# Create temporary directories\n",50        "temp_extract_dir = '/content/temp_extracted_for_split'\n",51        "temp_left_dir = '/content/temp_split_left'\n",52        "temp_middle_dir = '/content/temp_split_middle'\n",53        "temp_right_dir = '/content/temp_split_right'\n",54        "\n",55        "for d in [temp_extract_dir, temp_left_dir, temp_middle_dir, temp_right_dir]:\n",56        "    os.makedirs(d, exist_ok=True)\n",57        "\n",58        "print(f\"Processing zip file: {input_zip_path}\")\n",59        "\n",60        "try:\n",61        "    # 1. Open the input zip file and extract all images\n",62        "    with zipfile.ZipFile(input_zip_path, 'r') as zip_ref:\n",63        "        zip_ref.extractall(temp_extract_dir)\n",64        "    print(f\"Extracted contents to {temp_extract_dir}\")\n",65        "\n",66        "    # Get a sorted list of image files to maintain order\n",67        "    image_files = sorted([f for f in os.listdir(temp_extract_dir) if f.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp', '.webp'))])\n",68        "\n",69        "    if not image_files:\n",70        "        print(\"No image files found in the zip file. Exiting.\")\n",71        "    else:\n",72        "        print(f\"Found {len(image_files)} image files. Splitting...\")\n",73        "\n",74        "        # 2. Split all images along the horizontal axis into three equal parts\n",75        "        for i, img_filename in enumerate(image_files):\n",76        "            img_path = os.path.join(temp_extract_dir, img_filename)\n",77        "            try:\n",78        "                with Image.open(img_path) as img:\n",79        "                    width, height = img.size\n",80        "                    part_width = width // 3\n",81        "\n",82        "                    # Define the crop boxes for left, middle, and right parts\n",83        "                    left_box = (0, 0, part_width, height)\n",84        "                    middle_box = (part_width, 0, 2 * part_width, height)\n",85        "                    # The right box takes the remaining width to handle non-divisible widths\n",86        "                    right_box = (2 * part_width, 0, width, height)\n",87        "\n",88        "                    img_left = img.crop(left_box)\n",89        "                    img_middle = img.crop(middle_box)\n",90        "                    img_right = img.crop(right_box)\n",91        "\n",92        "                    # Save the split parts to their respective temporary directories\n",93        "                    # Use the original numbering (i+1) for consistency\n",94        "                    base_name, ext = os.path.splitext(img_filename)\n",95        "                    new_name_stem = str(i + 1)\n",96        "\n",97        "                    img_left.save(os.path.join(temp_left_dir, f'{new_name_stem}{ext}'))\n",98        "                    img_middle.save(os.path.join(temp_middle_dir, f'{new_name_stem}{ext}'))\n",99        "                    img_right.save(os.path.join(temp_right_dir, f'{new_name_stem}{ext}'))\n",100        "\n",101        "            except Exception as e:\n",102        "                print(f\"Error processing image {img_filename}: {e}\")\n",103        "\n",104        "        print(\"Images split successfully. Zipping parts...\")\n",105        "\n",106        "        # 3. Save the images in three separate zips\n",107        "        # Output zip paths\n",108        "        output_zip_left = os.path.join(dest_folder, f'{output_base_name}_left.zip')\n",109        "        output_zip_middle = os.path.join(dest_folder, f'{output_base_name}_middle.zip')\n",110        "        output_zip_right = os.path.join(dest_folder, f'{output_base_name}_right.zip')\n",111        "\n",112        "        # Create zip files\n",113        "        with zipfile.ZipFile(output_zip_left, 'w', zipfile.ZIP_DEFLATED) as zf_left:\n",114        "            for foldername, subfolders, filenames in os.walk(temp_left_dir):\n",115        "                for filename in filenames:\n",116        "                    filepath = os.path.join(foldername, filename)\n",117        "                    zf_left.write(filepath, os.path.relpath(filepath, temp_left_dir))\n",118        "        print(f\"Created {output_zip_left}\")\n",119        "\n",120        "        with zipfile.ZipFile(output_zip_middle, 'w', zipfile.ZIP_DEFLATED) as zf_middle:\n",121        "            for foldername, subfolders, filenames in os.walk(temp_middle_dir):\n",122        "                for filename in filenames:\n",123        "                    filepath = os.path.join(foldername, filename)\n",124        "                    zf_middle.write(filepath, os.path.relpath(filepath, temp_middle_dir))\n",125        "        print(f\"Created {output_zip_middle}\")\n",126        "\n",127        "        with zipfile.ZipFile(output_zip_right, 'w', zipfile.ZIP_DEFLATED) as zf_right:\n",128        "            for foldername, subfolders, filenames in os.walk(temp_right_dir):\n",129        "                for filename in filenames:\n",130        "                    filepath = os.path.join(foldername, filename)\n",131        "                    zf_right.write(filepath, os.path.relpath(filepath, temp_right_dir))\n",132        "        print(f\"Created {output_zip_right}\")\n",133        "\n",134        "except FileNotFoundError:\n",135        "    print(f\"Error: Input zip file not found at {input_zip_path}\")\n",136        "except Exception as e:\n",137        "    print(f\"An unexpected error occurred: {e}\")\n",138        "finally:\n",139        "    # Clean up temporary directories\n",140        "    for d in [temp_extract_dir, temp_left_dir, temp_middle_dir, temp_right_dir]:\n",141        "        if os.path.exists(d):\n",142        "            shutil.rmtree(d)\n",143        "            print(f\"Cleaned up {d}\")\n",144        "    print(\"Process finished.\")\n"145      ],146      "execution_count": null,147      "outputs": []148    }149  ]150}