Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-2024-08-06· OpenAIAi2 WildChat-4.8M (AI2)

I have a script. I want to modify the script slightly. I want to upload logo instead of…

  1. User

    I have a script. I want to modify the script slightly. I want to upload logo instead of just one. One will remain same as before and other want to put top left corner of photos as watermark. Here is my script= # Install necessary libraries !pip install pillow ipywidgets

    from PIL import Image, ImageEnhance from IPython.display import display, clear_output import ipywidgets as widgets from ipywidgets import interact from google.colab import drive from google.colab import files import zipfile import os

    Mount Google Drive

    drive.mount('/content/drive')

    Function to select file from Google Drive

    def select_file_from_drive(description): print('Select the file from your Google Drive') uploaded = files.upload() filename = list(uploaded.keys())[0] return filename

    Function to apply watermark

    def apply_watermark(image, watermark, opacity, scale_factor, flip): # Optionally flip the image horizontally if flip: image = image.transpose(method=Image.FLIP_LEFT_RIGHT)

    # Resize the watermark
    w_width = int(image.width * scale_factor)
    w_height = int(watermark.height * (w_width / watermark.width))
    resized_watermark = watermark.resize((w_width, w_height), Image.LANCZOS)
    
    # Ensure watermark has RGBA mode for transparency
    if resized_watermark.mode != 'RGBA':
        resized_watermark = resized_watermark.convert('RGBA')
    
    # Adjust opacity
    alpha = resized_watermark.split()[3]
    alpha = ImageEnhance.Brightness(alpha).enhance(opacity)
    resized_watermark.putalpha(alpha)
    
    # Position the watermark at the bottom center
    wm_position = ((image.width - resized_watermark.width) // 2,
                   image.height - resized_watermark.height - 10)  # 10 px from bottom
    
    # Paste the watermark onto the image
    transparent_image = Image.new('RGBA', image.size)
    transparent_image.paste(image, (0, 0))
    transparent_image.paste(resized_watermark, wm_position, mask=resized_watermark)
    return transparent_image
    

    Function to upload watermark image

    def upload_watermark(): print("Upload your watermark logo image:") uploaded = files.upload() watermark_path = list(uploaded.keys())[0] watermark_img = Image.open(watermark_path).convert("RGBA") return watermark_img

    Upload watermark image

    watermark_img = upload_watermark()

    Select and extract ZIP file from Google Drive

    zip_file_name = select_file_from_drive('Select your ZIP file:') zip_path = f'/content/{zip_file_name}' upload_folder = '/content/input_images' os.makedirs(upload_folder, exist_ok=True)

    with zipfile.ZipFile(zip_path, 'r') as zip_ref: zip_ref.extractall(upload_folder)

    Get the list of image filenames

    image_files = [f for f in os.listdir(upload_folder) if os.path.isfile(os.path.join(upload_folder, f))]

    Use the first image for preview

    first_image_path = os.path.join(upload_folder, image_files[0])

    Define widgets for user input

    slider_opacity = widgets.FloatSlider(value=0.5, min=0.0, max=1.0, step=0.1, description='Opacity:') slider_scale = widgets.FloatSlider(value=0.2, min=0.1, max=0.5, step=0.05, description='Scale:') toggle_flip = widgets.Checkbox(value=False, description='Flip Horizontally')

    Preview function

    def preview(opacity, scale_factor, flip): with Image.open(first_image_path) as sample_image: sample_image = sample_image.convert("RGBA") result = apply_watermark(sample_image, watermark_img, opacity, scale_factor, flip) clear_output(wait=True) display(result)

    Interactive preview

    interact(preview, opacity=slider_opacity, scale_factor=slider_scale, flip=toggle_flip)

    Directory for output images

    output_folder = '/content/output_images' os.makedirs(output_folder, exist_ok=True)

    Function to process all images

    def process_images(opacity, scale_factor, flip): output_files = [] for filename in image_files: input_image_path = os.path.join(upload_folder, filename) with Image.open(input_image_path) as img: img = img.convert("RGBA") watermarked_image = apply_watermark(img, watermark_img, opacity, scale_factor, flip) output_path = os.path.join(output_folder, filename) watermarked_image.save(output_path, "PNG") output_files.append(output_path)

    # Prepare ZIP file
    drive_output_zip = '/content/drive/My Drive/processed_images.zip'
    with zipfile.ZipFile(drive_output_zip, 'w') as zipf:
        for file in output_files:
            zipf.write(file, arcname=os.path.basename(file))
    
    print("Processed images are saved back to Google Drive.")
    

    Button to start processing images

    confirm_button = widgets.Button(description="Batch Process Images") confirm_button.on_click(lambda x: process_images(slider_opacity.value, slider_scale.value, toggle_flip.value))

    Display button

    display(confirm_button)

  2. Assistant

    To modify your script to add a second watermark in the top-left corner while keeping the existing functionality, you can create a new function for applying the second watermark and then integrate it within the existing workflow. Below is a modified version of your script that includes these changes:

    # Install necessary libraries
    !pip install pillow ipywidgets
    
    from PIL import Image, ImageEnhance
    from IPython.display import display, clear_output
    import ipywidgets as widgets
    from ipywidgets import interact
    from google.colab import drive
    from google.colab import files
    import zipfile
    import os
    
    # Mount Google Drive
    drive.mount('/content/drive')
    
    # Function to select file from Google Drive
    def select_file_from_drive(description):
        print('Select the file from your Google Drive')
        uploaded = files.upload()
        filename = list(uploaded.keys())[0]
        return filename
    
    # Function to apply watermark
    def apply_watermark(image, watermark_bottom, watermark_top, opacity, scale_factor, flip):
        # Optionally flip the image horizontally
        if flip:
            image = image.transpose(method=Image.FLIP_LEFT_RIGHT)
    
        # Preparing bottom watermark
        w_width = int(image.width * scale_factor)
        w_height = int(watermark_bottom.height * (w_width / watermark_bottom.width))
        resized_bottom = watermark_bottom.resize((w_width, w_height), Image.LANCZOS)
        
        # Preparing top-left watermark
        tl_width = int(image.width * 0.1)  # for example scaling factor for the top-left
        tl_height = int(watermark_top.height * (tl_width / watermark_top.width))
        resized_top = watermark_top.resize((tl_width, tl_height), Image.LANCZOS)
    
        # Ensure watermarks have RGBA mode for transparency
        if resized_bottom.mode != 'RGBA':
            resized_bottom = resized_bottom.convert('RGBA')
        if resized_top.mode != 'RGBA':
            resized_top = resized_top.convert('RGBA')
    
        # Adjust opacity
        alpha = resized_bottom.split()[3]
        alpha = ImageEnhance.Brightness(alpha).enhance(opacity)
        resized_bottom.putalpha(alpha)
    
        transparent_image = Image.new('RGBA', image.size)
        transparent_image.paste(image, (0, 0))
    
        # Position the bottom watermark
        wm_bottom_position = ((image.width - resized_bottom.width) // 2,
                              image.height - resized_bottom.height - 10)  # 10 px from bottom
    
        # Paste watermark at bottom center
        transparent_image.paste(resized_bottom, wm_bottom_position, mask=resized_bottom)
    
        # Position the top-left watermark
        wm_top_position = (10, 10)  # 10 px from top and left
    
        # Paste watermark at top-left corner
        transparent_image.paste(resized_top, wm_top_position, mask=resized_top)
    
        return transparent_image
    
    # Function to upload watermark images
    def upload_watermark(description):
        print(description)
        uploaded = files.upload()
        watermark_path = list(uploaded.keys())[0]
        watermark_img = Image.open(watermark_path).convert("RGBA")
        return watermark_img
    
    # Upload watermarks
    print("Upload bottom-center watermark.")
    watermark_bottom = upload_watermark("Upload your bottom-center watermark logo image:")
    print("Upload top-left watermark.")
    watermark_top = upload_watermark("Upload your top-left watermark logo image:")
    
    # Select and extract ZIP file from Google Drive
    zip_file_name = select_file_from_drive('Select your ZIP file:')
    zip_path = f'/content/{zip_file_name}'
    upload_folder = '/content/input_images'
    os.makedirs(upload_folder, exist_ok=True)
    
    with zipfile.ZipFile(zip_path, 'r') as zip_ref:
        zip_ref.extractall(upload_folder)
    
    # Get the list of image filenames
    image_files = [f for f in os.listdir(upload_folder) if os.path.isfile(os.path.join(upload_folder, f))]
    
    # Use the first image for preview
    first_image_path = os.path.join(upload_folder, image_files[0])
    
    # Define widgets for user input
    slider_opacity = widgets.FloatSlider(value=0.5, min=0.0, max=1.0, step=0.1, description='Opacity:')
    slider_scale = widgets.FloatSlider(value=0.2, min=0.1, max=0.5, step=0.05, description='Scale:')
    toggle_flip = widgets.Checkbox(value=False, description='Flip Horizontally')
    
    # Preview function
    def preview(opacity, scale_factor, flip):
        with Image.open(first_image_path) as sample_image:
            sample_image = sample_image.convert("RGBA")
            result = apply_watermark(sample_image, watermark_bottom, watermark_top, opacity, scale_factor, flip)
            clear_output(wait=True)
            display(result)
    
    # Interactive preview
    interact(preview, opacity=slider_opacity, scale_factor=slider_scale, flip=toggle_flip)
    
    # Directory for output images
    output_folder = '/content/output_images'
    os.makedirs(output_folder, exist_ok=True)
    
    # Function to process all images
    def process_images(opacity, scale_factor, flip):
        output_files = []
        for filename in image_files:
            input_image_path = os.path.join(upload_folder, filename)
            with Image.open(input_image_path) as img:
                img = img.convert("RGBA")
                watermarked_image = apply_watermark(img, watermark_bottom, watermark_top, opacity, scale_factor, flip)
                output_path = os.path.join(output_folder, filename)
                watermarked_image.save(output_path, "PNG")
                output_files.append(output_path)
    
        # Prepare ZIP file
        drive_output_zip = '/content/drive/My Drive/processed_images.zip'
        with zipfile.ZipFile(drive_output_zip, 'w') as zipf:
            for file in output_files:
                zipf.write(file, arcname=os.path.basename(file))
    
        print("Processed images are saved back to Google Drive.")
    
    # Button to start processing images
    confirm_button = widgets.Button(description="Batch Process Images")
    confirm_button.on_click(lambda x: process_images(slider_opacity.value, slider_scale.value, toggle_flip.value))
    
    # Display button
    display(confirm_button)
    

    Explanation:

    1. Two Watermark Uploads: The script now includes an additional call to upload_watermark for the top-left corner watermark, allowing you to upload two separate watermark images.

    2. Watermark Resizing and Position: The script separately resizes and positions both watermarks. The existing watermark logic orchestrates the bottom watermark, and new logic is applied to resize and position the top one at the coordinates (10, 10) (top-left corner).

    3. Opacity Control: The opacity is only controlled globally through the opacity slider for the bottom watermark. You may adjust this separately for the second one if needed by replicating the opacity control logic.

    4. Batch Processing and Interaction: The interactive preview and batch processing functions (preview and process_images) are updated to use the newly defined apply_watermark function with both watermarks. The user interface elements remain intact to provide an adjustable interface for scaling, flipping, and watermark opacity.

  3. User

    There should be available opacity and size control for both watermark logos seperate separate.

  4. Assistant

    To provide separate controls for opacity and size for both watermarks, you need to create distinct widget controls for each watermark's opacity and scale. Then, adjust the apply_watermark function to use these independent values. Here's how you can modify your script:

    # Install necessary libraries
    !pip install pillow ipywidgets
    
    from PIL import Image, ImageEnhance
    from IPython.display import display, clear_output
    import ipywidgets as widgets
    from ipywidgets import interact
    from google.colab import drive
    from google.colab import files
    import zipfile
    import os
    
    # Mount Google Drive
    drive.mount('/content/drive')
    
    # Function to select file from Google Drive
    def select_file_from_drive(description):
        print('Select the file from your Google Drive')
        uploaded = files.upload()
        filename = list(uploaded.keys())[0]
        return filename
    
    # Function to apply watermark
    def apply_watermark(image, watermark_bottom, watermark_top, opacity_bottom, scale_bottom, opacity_top, scale_top, flip):
        # Optionally flip the image horizontally
        if flip:
            image = image.transpose(method=Image.FLIP_LEFT_RIGHT)
    
        # Preparing bottom watermark
        w_width_bottom = int(image.width * scale_bottom)
        w_height_bottom = int(watermark_bottom.height * (w_width_bottom / watermark_bottom.width))
        resized_bottom = watermark_bottom.resize((w_width_bottom, w_height_bottom), Image.LANCZOS)
        
        # Preparing top-left watermark
        w_width_top = int(image.width * scale_top)
        w_height_top = int(watermark_top.height * (w_width_top / watermark_top.width))
        resized_top = watermark_top.resize((w_width_top, w_height_top), Image.LANCZOS)
    
        # Ensure watermarks have RGBA mode for transparency
        if resized_bottom.mode != 'RGBA':
            resized_bottom = resized_bottom.convert('RGBA')
        if resized_top.mode != 'RGBA':
            resized_top = resized_top.convert('RGBA')
    
        # Adjust opacity for bottom watermark
        alpha_bottom = resized_bottom.split()[3]
        alpha_bottom = ImageEnhance.Brightness(alpha_bottom).enhance(opacity_bottom)
        resized_bottom.putalpha(alpha_bottom)
    
        # Adjust opacity for top-left watermark
        alpha_top = resized_top.split()[3]
        alpha_top = ImageEnhance.Brightness(alpha_top).enhance(opacity_top)
        resized_top.putalpha(alpha_top)
    
        transparent_image = Image.new('RGBA', image.size)
        transparent_image.paste(image, (0, 0))
    
        # Position the bottom watermark
        wm_bottom_position = ((image.width - resized_bottom.width) // 2,
                              image.height - resized_bottom.height - 10)  # 10 px from bottom
    
        # Paste watermark at the bottom center
        transparent_image.paste(resized_bottom, wm_bottom_position, mask=resized_bottom)
    
        # Position the top-left watermark
        wm_top_position = (10, 10)  # 10 px from top and left
    
        # Paste watermark at top-left corner
        transparent_image.paste(resized_top, wm_top_position, mask=resized_top)
    
        return transparent_image
    
    # Function to upload watermark images
    def upload_watermark(description):
        print(description)
        uploaded = files.upload()
        watermark_path = list(uploaded.keys())[0]
        watermark_img = Image.open(watermark_path).convert("RGBA")
        return watermark_img
    
    # Upload watermarks
    print("Upload bottom-center watermark.")
    watermark_bottom = upload_watermark("Upload your bottom-center watermark logo image:")
    print("Upload top-left watermark.")
    watermark_top = upload_watermark("Upload your top-left watermark logo image:")
    
    # Select and extract ZIP file from Google Drive
    zip_file_name = select_file_from_drive('Select your ZIP file:')
    zip_path = f'/content/{zip_file_name}'
    upload_folder = '/content/input_images'
    os.makedirs(upload_folder, exist_ok=True)
    
    with zipfile.ZipFile(zip_path, 'r') as zip_ref:
        zip_ref.extractall(upload_folder)
    
    # Get the list of image filenames
    image_files = [f for f in os.listdir(upload_folder) if os.path.isfile(os.path.join(upload_folder, f))]
    
    # Use the first image for preview
    first_image_path = os.path.join(upload_folder, image_files[0])
    
    # Define widgets for user input
    slider_opacity_bottom = widgets.FloatSlider(value=0.5, min=0.0, max=1.0, step=0.1, description='Bottom Opacity:')
    slider_scale_bottom = widgets.FloatSlider(value=0.2, min=0.1, max=0.5, step=0.05, description='Bottom Scale:')
    slider_opacity_top = widgets.FloatSlider(value=0.5, min=0.0, max=1.0, step=0.1, description='Top Opacity:')
    slider_scale_top = widgets.FloatSlider(value=0.1, min=0.05, max=0.2, step=0.05, description='Top Scale:')
    toggle_flip = widgets.Checkbox(value=False, description='Flip Horizontally')
    
    # Preview function
    def preview(opacity_bottom, scale_bottom, opacity_top, scale_top, flip):
        with Image.open(first_image_path) as sample_image:
            sample_image = sample_image.convert("RGBA")
            result = apply_watermark(sample_image, watermark_bottom, watermark_top, opacity_bottom, scale_bottom, opacity_top, scale_top, flip)
            clear_output(wait=True)
            display(result)
    
    # Interactive preview
    interact(preview, opacity_bottom=slider_opacity_bottom, scale_bottom=slider_scale_bottom, 
             opacity_top=slider_opacity_top, scale_top=slider_scale_top, flip=toggle_flip)
    
    # Directory for output images
    output_folder = '/content/output_images'
    os.makedirs(output_folder, exist_ok=True)
    
    # Function to process all images
    def process_images(opacity_bottom, scale_bottom, opacity_top, scale_top, flip):
        output_files = []
        for filename in image_files:
            input_image_path = os.path.join(upload_folder, filename)
            with Image.open(input_image_path) as img:
                img = img.convert("RGBA")
                watermarked_image = apply_watermark(img, watermark_bottom, watermark_top, opacity_bottom, scale_bottom, opacity_top, scale_top, flip)
                output_path = os.path.join(output_folder, filename)
                watermarked_image.save(output_path, "PNG")
                output_files.append(output_path)
    
        # Prepare ZIP file
        drive_output_zip = '/content/drive/My Drive/processed_images.zip'
        with zipfile.ZipFile(drive_output_zip, 'w') as zipf:
            for file in output_files:
                zipf.write(file, arcname=os.path.basename(file))
    
        print("Processed images are saved back to Google Drive.")
    
    # Button to start processing images
    confirm_button = widgets.Button(description="Batch Process Images")
    confirm_button.on_click(lambda x: process_images(slider_opacity_bottom.value, slider_scale_bottom.value, 
                                                     slider_opacity_top.value, slider_scale_top.value, toggle_flip.value))
    
    # Display button
    display(confirm_button)
    

    Key Modifications:

    1. Separate Widgets for Each Watermark: Four sliders are created:

      • slider_opacity_bottom: Controls the opacity of the bottom-center watermark.
      • slider_scale_bottom: Controls the scale of the bottom-center watermark.
      • slider_opacity_top: Controls the opacity of the top-left watermark.
      • slider_scale_top: Controls the scale of the top-left watermark.
    2. Updated apply_watermark Function: Instead of using shared opacity and scale_factor for both watermarks, it now uses separate ones based on the new sliders.

    3. Interactive Preview and Processing: Adjustments are made to preview and process_images to use the individual slider values for watermark control.

    With these changes, you can control the opacity and size of each watermark individually.