image-collage / app.py
szk1ck's picture
bug fix
a0de3ed
raw
history blame
2.76 kB
import gradio as gr
import cv2
import numpy as np
import random
from PIL import Image
def resize_with_fixed_aspect_ratio(image, new_metrics, size_metrics="height"):
height, width = image.shape[:2]
# print("new_metrics in functions", new_metrics)
# print("before:", image.shape)
if size_metrics=="height":
aspect_ratio = width / height
# print("aspect_ratio: ", aspect_ratio)
new_height = new_metrics
new_width = int(new_height * aspect_ratio)
elif size_metrics=="width":
aspect_ratio = height / width
new_width = new_metrics
new_height = int(new_width * aspect_ratio)
new_size = (new_height, new_width)
new_size = (new_width, new_height)
# print("new_size: ", new_size)
resized_image = cv2.resize(image, dsize=new_size, interpolation=cv2.INTER_CUBIC)
# print("after:", resized_image.shape)
return resized_image
def show_image(obj_image, bg_image):
bg_height, bg_width = bg_image.shape[:2]
obj_height, obj_width = obj_image.shape[:2]
if obj_height>obj_width:
size_metrics="height"
if bg_height>obj_height:
resize_min_rate = bg_height/obj_height
new_metrics = bg_height
else:
resize_min_rate = obj_height/bg_height
new_metrics = obj_height
elif obj_height<obj_width:
size_metrics="width"
if bg_height>obj_height:
resize_min_rate = bg_width/obj_width
new_metrics = bg_width
else:
resize_min_rate = obj_width/bg_width
new_metrics = obj_width
obj_vs_bg = random.uniform(resize_min_rate, resize_min_rate+5)
obj_image = resize_with_fixed_aspect_ratio(obj_image, int(new_metrics/obj_vs_bg), size_metrics)
height, width = obj_image.shape[:2]
result_image = bg_image.copy()
max_x = bg_width-width
max_y = bg_height-height
try:
move_x = random.randint(0, max_x)
move_y = random.randint(0, max_y)
result_image[move_y:move_y+height, move_x:move_x+width, :] = obj_image
except:
print("bg_width.shape: ", bg_image.shape)
print("obj_image.shape: ", obj_image.shape)
print("max_y: ", max_y)
print("max_x: ", max_x)
print("obj_vs_bg", obj_vs_bg)
print("resize_min_rate", resize_min_rate)
result_image = np.where(result_image>0, result_image, bg_image)
return result_image
image_input_obj = gr.Image(type="numpy")
image_input_bg = gr.Image(type="numpy")
image_output = gr.Image(type="numpy")
iface = gr.Interface(
fn=show_image,
inputs=[
image_input_obj,
image_input_bg
],
outputs=image_output
)
iface.launch()