|
import logging
|
|
import azure.functions as func
|
|
from PIL import Image
|
|
import io
|
|
import torch
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
|
|
module_path = Path(__file__).parent / 'RMBG'
|
|
sys.path.append(str(module_path))
|
|
|
|
from briarmbg import BriaRMBG
|
|
from utilities import preprocess_image, postprocess_image
|
|
import numpy as np
|
|
|
|
app = func.FunctionApp(http_auth_level=func.AuthLevel.ANONYMOUS)
|
|
|
|
|
|
def resize_image(image, target_width=1440, target_height=1440):
|
|
original_width, original_height = image.size
|
|
|
|
|
|
aspect_ratio = original_width / original_height
|
|
|
|
|
|
if aspect_ratio > 1:
|
|
new_width = target_width
|
|
new_height = int(target_width / aspect_ratio)
|
|
else:
|
|
new_height = target_height
|
|
new_width = int(target_height * aspect_ratio)
|
|
|
|
|
|
resized_img = image.resize((new_width, new_height), Image.LANCZOS)
|
|
|
|
return resized_img
|
|
|
|
|
|
net = BriaRMBG()
|
|
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
|
net = BriaRMBG.from_pretrained("briaai/RMBG-1.4")
|
|
net.to(device)
|
|
net.eval()
|
|
|
|
@app.route(route="processimage")
|
|
def process_image(req: func.HttpRequest) -> func.HttpResponse:
|
|
logging.info('Python HTTP trigger function processed a request.')
|
|
|
|
try:
|
|
|
|
image_data = req.get_body()
|
|
input_image = Image.open(io.BytesIO(image_data))
|
|
|
|
|
|
resized_image = resize_image(input_image)
|
|
|
|
|
|
model_input_size = [1024, 1024]
|
|
image = preprocess_image(np.array(resized_image), model_input_size).to(device)
|
|
|
|
|
|
result = net(image)
|
|
|
|
|
|
result_image = postprocess_image(result[0][0], input_image.size)
|
|
|
|
|
|
pil_im = Image.fromarray(result_image)
|
|
|
|
|
|
white_bg = Image.new("RGBA", (1440, 2560), (255, 255, 255, 255))
|
|
|
|
|
|
mask_resized = pil_im.resize(resized_image.size, Image.LANCZOS)
|
|
|
|
|
|
x_offset = (white_bg.width - resized_image.width) // 2
|
|
y_offset = white_bg.height - resized_image.height - 100
|
|
|
|
|
|
white_bg.paste(resized_image, (x_offset, y_offset), mask=mask_resized)
|
|
|
|
|
|
output_buffer = io.BytesIO()
|
|
white_bg.save(output_buffer, format="PNG")
|
|
output_buffer.seek(0)
|
|
|
|
return func.HttpResponse(output_buffer.read(), mimetype="image/png")
|
|
|
|
except Exception as e:
|
|
logging.error(f"Error processing the image: {e}")
|
|
return func.HttpResponse(f"Error processing the image: {e}", status_code=500)
|
|
|