oshita-n commited on
Commit
a6170f9
·
1 Parent(s): 58a4384

first commit

Browse files
Files changed (1) hide show
  1. app.py +59 -0
app.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import cv2
3
+ import requests
4
+ import numpy as np
5
+ from PIL import Image
6
+ from io import BytesIO
7
+ from rembg import remove
8
+ from diffusers import StableDiffusionControlNetPipeline, ControlNetModel
9
+ import torch
10
+
11
+ def remove_background(input_image: Image.Image, to_grayscale: bool) -> Image.Image:
12
+ output_image = remove(input_image)
13
+ if to_grayscale:
14
+ output_image = convert_to_grayscale(output_image)
15
+ return output_image
16
+
17
+ def convert_to_grayscale(image: Image.Image) -> Image.Image:
18
+ return image.convert("L")
19
+
20
+ def canny_image(image: Image.Image) -> Image.Image:
21
+ np_image = np.array(image)
22
+ low_threshold = 100
23
+ high_threshold = 200
24
+ np_image = cv2.Canny(np_image, low_threshold, high_threshold)
25
+ np_image = np_image[:, :, None]
26
+ np_image = np.concatenate([np_image, np_image, np_image], axis=2)
27
+ return Image.fromarray(np_image)
28
+
29
+ def process_image(input_image: Image.Image, to_grayscale: bool, prompt: str) -> Image.Image:
30
+ output_image = remove_background(input_image, to_grayscale)
31
+ canny_output = canny_image(output_image)
32
+
33
+ controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny", torch_dtype=torch.float16)
34
+ pipe = StableDiffusionControlNetPipeline.from_pretrained(
35
+ "runwayml/stable-diffusion-v1-5", controlnet=controlnet, torch_dtype=torch.float16
36
+ )
37
+
38
+ output = pipe(
39
+ [prompt],
40
+ canny_output,
41
+ negative_prompt=["monochrome, lowres, bad anatomy, worst quality, low quality"],
42
+ generator=[torch.Generator(device="cpu").manual_seed(2)],
43
+ num_inference_steps=20,
44
+ )
45
+
46
+ return image_grid(output.images, 1, 1)
47
+
48
+ image_input = gr.components.Image(label="Input Image")
49
+ grayscale_checkbox = gr.components.Checkbox(label="Convert output to grayscale", default=False)
50
+ prompt_input = gr.components.Textbox(lines=1, label="Prompt")
51
+ image_output = gr.components.Image(label="Output Image", type="pil")
52
+
53
+ gr.Interface(
54
+ fn=process_image,
55
+ inputs=[image_input, grayscale_checkbox, prompt_input],
56
+ outputs=image_output,
57
+ title="Background Removal",
58
+ description="Upload an image to remove its background and optionally convert it to grayscale",
59
+ ).launch()