Spaces:
Sleeping
Sleeping
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() |