File size: 12,732 Bytes
06a7897
1
{"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"provenance":[],"authorship_tag":"ABX9TyNIWXPr/tkeegtSblfnxptk"},"kernelspec":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"}},"cells":[{"cell_type":"code","source":["from google.colab import drive\n","drive.mount('/content/drive')"],"metadata":{"id":"WHDPLITy4Rh0"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["create_one_of_each = True  #@param {type:\"boolean\"}"],"metadata":{"cellView":"form","id":"hEnouo304I5i","executionInfo":{"status":"ok","timestamp":1780228342649,"user_tz":-120,"elapsed":73,"user":{"displayName":"No Name","userId":"10578412414437288386"}}},"execution_count":9,"outputs":[]},{"cell_type":"code","execution_count":12,"metadata":{"id":"eXtw5dri09j5","executionInfo":{"status":"ok","timestamp":1780228434476,"user_tz":-120,"elapsed":5,"user":{"displayName":"No Name","userId":"10578412414437288386"}}},"outputs":[],"source":["# =============================================================================\n","# USER SETTINGS\n","# =============================================================================\n","\n","input_zip = \"/content/drive/MyDrive/to_add_print.zip\"  #@param {type:\"string\"}\n","output_zip_name = \"effects_output.zip\"  #@param {type:\"string\"}\n","\n","enable_gaussian_blur = True  #@param {type:\"boolean\"}\n","blur_strength = 5  #@param {type:\"slider\", min:1, max:51, step:2}\n","\n","enable_motion_blur = True  #@param {type:\"boolean\"}\n","motion_blur_size = 15  #@param {type:\"slider\", min:3, max:101, step:2}\n","\n","enable_bloom = True  #@param {type:\"boolean\"}\n","bloom_strength = 1.0  #@param {type:\"slider\", min:0.1, max:5.0, step:0.1}\n","\n","enable_chromatic_aberration = True  #@param {type:\"boolean\"}\n","chromatic_shift = 5  #@param {type:\"slider\", min:1, max:50, step:1}\n","\n","enable_vignette = True  #@param {type:\"boolean\"}\n","vignette_strength = 0.5  #@param {type:\"slider\", min:0.0, max:1.0, step:0.05}\n","\n","enable_fisheye = True  #@param {type:\"boolean\"}\n","fisheye_strength = 0.3  #@param {type:\"slider\", min:0.0, max:1.0, step:0.05}\n","\n","enable_swirl = True  #@param {type:\"boolean\"}\n","swirl_strength = 5.0  #@param {type:\"slider\", min:0.0, max:20.0, step:0.5}\n","\n","enable_wave_distortion = True  #@param {type:\"boolean\"}\n","wave_amplitude = 20  #@param {type:\"slider\", min:1, max:100, step:1}\n","\n","enable_glow = True  #@param {type:\"boolean\"}\n","glow_strength = 1.0  #@param {type:\"slider\", min:0.1, max:5.0, step:0.1}\n","\n","enable_pixelation = True  #@param {type:\"boolean\"}\n","pixelation_strength = 8  #@param {type:\"slider\", min:2, max:64, step:2}\n","\n","\n"]},{"cell_type":"code","source":["!pip install -q opencv-python pillow scikit-image tqdm"],"metadata":{"id":"PHCGi8kU1Ha8","executionInfo":{"status":"ok","timestamp":1780227989108,"user_tz":-120,"elapsed":9991,"user":{"displayName":"No Name","userId":"10578412414437288386"}}},"execution_count":3,"outputs":[]},{"cell_type":"code","source":["import os\n","import cv2\n","import zipfile\n","import shutil\n","import numpy as np\n","\n","from PIL import Image\n","from tqdm import tqdm\n","from skimage.transform import swirl"],"metadata":{"id":"AVbnlOLQ1SIz","executionInfo":{"status":"ok","timestamp":1780227989599,"user_tz":-120,"elapsed":494,"user":{"displayName":"No Name","userId":"10578412414437288386"}}},"execution_count":4,"outputs":[]},{"cell_type":"code","source":["INPUT_DIR = \"/content/input_images\"\n","OUTPUT_DIR = \"/content/output_images\"\n","\n","if os.path.exists(INPUT_DIR):\n","    shutil.rmtree(INPUT_DIR)\n","\n","if True:   #os.path.exists(OUTPUT_DIR):\n","    shutil.rmtree(OUTPUT_DIR)\n","\n","os.makedirs(INPUT_DIR)\n","os.makedirs(OUTPUT_DIR)"],"metadata":{"id":"dCyNIofo3CqG","executionInfo":{"status":"ok","timestamp":1780228440003,"user_tz":-120,"elapsed":42,"user":{"displayName":"No Name","userId":"10578412414437288386"}}},"execution_count":13,"outputs":[]},{"cell_type":"code","source":["with zipfile.ZipFile(input_zip, \"r\") as z:\n","    z.extractall(INPUT_DIR)\n","\n","print(\"ZIP extracted\")"],"metadata":{"id":"Qzf9B6Kk1hMp"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["def gaussian_blur(img):\n","    return cv2.GaussianBlur(\n","        img,\n","        (blur_strength, blur_strength),\n","        0\n","    )\n","\n","def motion_blur(img):\n","    kernel = np.zeros((motion_blur_size, motion_blur_size))\n","    kernel[int((motion_blur_size - 1) / 2), :] = np.ones(motion_blur_size)\n","    kernel = kernel / motion_blur_size\n","    return cv2.filter2D(img, -1, kernel)\n","\n","def bloom(img):\n","    blur = cv2.GaussianBlur(img, (0,0), 25)\n","    return cv2.addWeighted(\n","        img,\n","        1.0,\n","        blur,\n","        bloom_strength,\n","        0\n","    )\n","\n","def glow(img):\n","    blur = cv2.GaussianBlur(img, (0,0), 15)\n","    return cv2.addWeighted(\n","        img,\n","        1.0,\n","        blur,\n","        glow_strength,\n","        0\n","    )\n","\n","def chromatic_aberration(img):\n","    b,g,r = cv2.split(img)\n","\n","    r = np.roll(r, chromatic_shift, axis=1)\n","    b = np.roll(b, -chromatic_shift, axis=1)\n","\n","    return cv2.merge([b,g,r])\n","\n","def vignette(img):\n","    rows, cols = img.shape[:2]\n","\n","    kernel_x = cv2.getGaussianKernel(cols, cols*vignette_strength)\n","    kernel_y = cv2.getGaussianKernel(rows, rows*vignette_strength)\n","\n","    kernel = kernel_y * kernel_x.T\n","    mask = kernel/kernel.max()\n","\n","    return (img * mask[:,:,None]).astype(np.uint8)\n","\n","def fisheye(img):\n","    h,w = img.shape[:2]\n","\n","    map_x = np.zeros((h,w), np.float32)\n","    map_y = np.zeros((h,w), np.float32)\n","\n","    cx = w/2\n","    cy = h/2\n","\n","    for y in range(h):\n","        for x in range(w):\n","\n","            nx = (x-cx)/cx\n","            ny = (y-cy)/cy\n","\n","            r = np.sqrt(nx*nx+ny*ny)\n","\n","            if r == 0:\n","                factor = 1\n","            else:\n","                factor = 1 + fisheye_strength*r*r\n","\n","            map_x[y,x] = cx + nx*cx*factor\n","            map_y[y,x] = cy + ny*cy*factor\n","\n","    return cv2.remap(\n","        img,\n","        map_x,\n","        map_y,\n","        cv2.INTER_LINEAR\n","    )\n","\n","def swirl_effect(img):\n","\n","    result = swirl(\n","        img,\n","        strength=swirl_strength,\n","        radius=min(img.shape[:2])//2\n","    )\n","\n","    return (result*255).astype(np.uint8)\n","\n","def wave_distort(img):\n","\n","    h,w = img.shape[:2]\n","\n","    output = np.zeros_like(img)\n","\n","    for y in range(h):\n","\n","        shift = int(\n","            wave_amplitude *\n","            np.sin(2*np.pi*y/128)\n","        )\n","\n","        output[y] = np.roll(\n","            img[y],\n","            shift,\n","            axis=0\n","        )\n","\n","    return output\n","\n","def pixelate(img):\n","\n","    h,w = img.shape[:2]\n","\n","    small = cv2.resize(\n","        img,\n","        (max(1,w//pixelation_strength),\n","         max(1,h//pixelation_strength)),\n","        interpolation=cv2.INTER_LINEAR\n","    )\n","\n","    return cv2.resize(\n","        small,\n","        (w,h),\n","        interpolation=cv2.INTER_NEAREST\n","    )"],"metadata":{"id":"hFqvs6Aq1j4n","executionInfo":{"status":"ok","timestamp":1780228447417,"user_tz":-120,"elapsed":17,"user":{"displayName":"No Name","userId":"10578412414437288386"}}},"execution_count":14,"outputs":[]},{"cell_type":"code","source":["VALID_EXTS = (\n","    \".png\",\n","    \".jpg\",\n","    \".jpeg\",\n","    \".webp\",\n","    \".bmp\"\n",")\n","\n","EFFECTS = {\n","    \"gaussian_blur\": gaussian_blur,\n","    \"motion_blur\": motion_blur,\n","    \"bloom\": bloom,\n","    \"glow\": glow,\n","    \"chromatic_aberration\": chromatic_aberration,\n","    \"vignette\": vignette,\n","    \"fisheye\": fisheye,\n","    \"swirl\": swirl_effect,\n","    \"wave_distortion\": wave_distort,\n","    \"pixelation\": pixelate,\n","}\n","\n","ENABLED_EFFECTS = []\n","\n","if enable_gaussian_blur:\n","    ENABLED_EFFECTS.append(\"gaussian_blur\")\n","\n","if enable_motion_blur:\n","    ENABLED_EFFECTS.append(\"motion_blur\")\n","\n","if enable_bloom:\n","    ENABLED_EFFECTS.append(\"bloom\")\n","\n","if enable_glow:\n","    ENABLED_EFFECTS.append(\"glow\")\n","\n","if enable_chromatic_aberration:\n","    ENABLED_EFFECTS.append(\"chromatic_aberration\")\n","\n","if enable_vignette:\n","    ENABLED_EFFECTS.append(\"vignette\")\n","\n","if enable_fisheye:\n","    ENABLED_EFFECTS.append(\"fisheye\")\n","\n","if enable_swirl:\n","    ENABLED_EFFECTS.append(\"swirl\")\n","\n","if enable_wave_distortion:\n","    ENABLED_EFFECTS.append(\"wave_distortion\")\n","\n","if enable_pixelation:\n","    ENABLED_EFFECTS.append(\"pixelation\")\n","\n","\n","if create_one_of_each:\n","\n","    print(\"Creating one folder per effect...\")\n","\n","    for effect_name in ENABLED_EFFECTS:\n","\n","        effect_dir = os.path.join(\n","            OUTPUT_DIR,\n","            effect_name\n","        )\n","\n","        os.makedirs(\n","            effect_dir,\n","            exist_ok=True\n","        )\n","\n","        effect_fn = EFFECTS[effect_name]\n","\n","        for root, _, files in os.walk(INPUT_DIR):\n","\n","            for file in tqdm(\n","                files,\n","                desc=effect_name\n","            ):\n","\n","                if not file.lower().endswith(\n","                    VALID_EXTS\n","                ):\n","                    continue\n","\n","                try:\n","\n","                    src = os.path.join(\n","                        root,\n","                        file\n","                    )\n","\n","                    img = cv2.imread(src)\n","\n","                    if img is None:\n","                        continue\n","\n","                    img = effect_fn(img)\n","\n","                    dst = os.path.join(\n","                        effect_dir,\n","                        file\n","                    )\n","\n","                    cv2.imwrite(\n","                        dst,\n","                        img\n","                    )\n","\n","                except Exception as e:\n","\n","                    print(\n","                        f\"Failed: {effect_name}/{file}\"\n","                    )\n","\n","                    print(e)\n","\n","else:\n","\n","    print(\"Creating combined effect output...\")\n","\n","    for root, _, files in os.walk(INPUT_DIR):\n","\n","        for file in tqdm(files):\n","\n","            if not file.lower().endswith(\n","                VALID_EXTS\n","            ):\n","                continue\n","\n","            try:\n","\n","                src = os.path.join(\n","                    root,\n","                    file\n","                )\n","\n","                img = cv2.imread(src)\n","\n","                if img is None:\n","                    continue\n","\n","                for effect_name in ENABLED_EFFECTS:\n","\n","                    img = EFFECTS[\n","                        effect_name\n","                    ](img)\n","\n","                dst = os.path.join(\n","                    OUTPUT_DIR,\n","                    file\n","                )\n","\n","                cv2.imwrite(\n","                    dst,\n","                    img\n","                )\n","\n","            except Exception as e:\n","\n","                print(\n","                    f\"Failed: {file}\"\n","                )\n","\n","                print(e)"],"metadata":{"id":"ecutfHOh4WW-"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["import random\n","import zipfile\n","import os\n","\n","random_id = random.randint(\n","    10000,\n","    99999\n",")\n","\n","output_zip_path = (\n","    f\"/content/drive/MyDrive/\"\n","    f\"sfx_images_{random_id}.zip\"\n",")\n","\n","with zipfile.ZipFile(\n","    output_zip_path,\n","    \"w\",\n","    zipfile.ZIP_DEFLATED\n",") as z:\n","\n","    for root, _, files in os.walk(\n","        OUTPUT_DIR\n","    ):\n","\n","        for file in files:\n","\n","            full_path = os.path.join(\n","                root,\n","                file\n","            )\n","\n","            arcname = os.path.relpath(\n","                full_path,\n","                OUTPUT_DIR\n","            )\n","\n","            z.write(\n","                full_path,\n","                arcname=arcname\n","            )\n","\n","print()\n","print(\"Done!\")\n","print(output_zip_path)"],"metadata":{"id":"G9yr0yBG5J1M"},"execution_count":null,"outputs":[]}]}