File size: 2,403 Bytes
0ff586f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad374a0
b4d5647
127f9db
b4d5647
0ff586f
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import gradio as gr
import cv2
import numpy as np
from PIL import Image

def hex_to_rgb(hex_code):
    # Remove the '#' symbol if present
    hex_code = hex_code.lstrip('#')
    
    # Convert the hex code to RGB
    return tuple(int(hex_code[i:i+2], 16) for i in (0, 2, 4))

def resize_and_overlay_image(input_image, reduction_percentage, shift_pixels, shift_pixels_ud, background_color):
    # Check if the input image is empty
    if input_image.size == 0:
        return None

    img = np.array(input_image)

    # Check if the image has shape information
    if img.ndim < 2:
        return None

    # Get the image dimensions
    height, width = img.shape[:2]

    # Calculate the new dimensions based on the reduction percentage
    new_height = int(height * reduction_percentage / 100)
    new_width = int(width * reduction_percentage / 100)

    # Resize the image
    resized_img = cv2.resize(img, (new_width, new_height))

    # Convert the hex code to RGB
    background_rgb = hex_to_rgb(background_color)

    # Create a background image with the original image dimensions and specified color
    background_img = np.ones((height, width, 3), dtype=np.uint8) * background_rgb

    # Calculate the position to overlay the resized image on the background image
    x = int((width - new_width) / 2) + int(shift_pixels)
    y = int((height - new_height) / 2) + int(shift_pixels_ud)

    # Overlay the resized image on the background image
    background_img[y:y + new_height, x:x + new_width] = resized_img

    # Return the resulting image as a NumPy array
    return background_img

# Create the Gradio interface
iface = gr.Interface(
    fn=resize_and_overlay_image,
    inputs=[
        gr.inputs.Image(type="pil", label="Input Image"),
        gr.inputs.Slider(minimum=0, maximum=100, step=10, default=80, label="Percentage of Original"),
        gr.inputs.Slider(minimum=-150, maximum=150, step=10, default=0, label="Shift Pixels Left / Right"),
        gr.inputs.Slider(minimum=-150, maximum=250, step=10, default=0, label="Shift Pixels Up / Down"),
        gr.inputs.Textbox(default="#ffffff", label="Background Color (Hex Code)")
    ],
    outputs=gr.outputs.Image(type="numpy", label="Result"),
    title="Image Resizer",
    description="Reduce the size of an image and overlay it on a colored background and shift it to the right."
)

if __name__ == "__main__":
    iface.launch()