import gradio as gr
import numpy as np
from PIL import Image
from rembg import remove
import base64
from io import BytesIO
# Placeholder for a very basic "image generation" - creates a colored square
def generate_image(color="red"):
if color == "red":
img_array = np.array([[[255, 0, 0] for _ in range(256)] for _ in range(256)], dtype=np.uint8)
elif color == "green":
img_array = np.array([[[0, 255, 0] for _ in range(256)] for _ in range(256)], dtype=np.uint8)
elif color == "blue":
img_array = np.array([[[0, 0, 255] for _ in range(256)] for _ in range(256)], dtype=np.uint8)
else:
img_array = np.array([[[255, 255, 255] for _ in range(256)] for _ in range(256)], dtype=np.uint8)
return Image.fromarray(img_array)
def remove_background(input_image):
if input_image is None:
return None
return remove(input_image)
# Placeholder for 3D conversion - just adds a border
def convert_to_3d(input_image):
if input_image is None:
return None
img = np.array(input_image)
height, width, _ = img.shape
border_size = 10
new_img = np.zeros((height + 2 * border_size, width + 2 * border_size, 3), dtype=np.uint8)
new_img[border_size:height + border_size, border_size:width + border_size] = img
new_img[:border_size, :, :] = [150,150,150]
new_img[height + border_size:, :, :] = [150,150,150]
new_img[:, :border_size, :] = [150,150,150]
new_img[:, width + border_size:, :] = [150,150,150]
return Image.fromarray(new_img)
def pil_to_base64(pil_image):
buffered = BytesIO()
pil_image.save(buffered, format="PNG")
img_str = base64.b64encode(buffered.getvalue()).decode()
return f"data:image/png;base64,{img_str}"
with gr.Blocks() as demo:
with gr.Row():
with gr.Column():
color_dropdown = gr.Dropdown(choices=["red", "green", "blue", "white"], label="Image Color")
generate_button = gr.Button("Generate Image")
generated_image = gr.Image(label="Generated Image")
remove_bg_button = gr.Button("Remove Background")
removed_bg_image = gr.Image(label="Background Removed Image")
convert_3d_button = gr.Button("Convert to 3D")
converted_3d_image = gr.Image(label="3D Converted Image")
generate_button.click(generate_image, inputs=[color_dropdown], outputs=[generated_image])
remove_bg_button.click(remove_background, inputs=[generated_image], outputs=[removed_bg_image])
convert_3d_button.click(convert_to_3d, inputs=[removed_bg_image], outputs=[converted_3d_image])
demo.launch()
# Same syntax as requirements.txt
pillow
rembg
numpy