codic commited on
Commit
491e6a9
·
verified ·
1 Parent(s): b74446e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -16
app.py CHANGED
@@ -10,6 +10,7 @@ import open3d as o3d
10
  from pathlib import Path
11
  import os
12
  import cv2
 
13
  from rembg import remove
14
  from gradio_client import Client
15
  import requests
@@ -21,26 +22,34 @@ feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
21
  model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")
22
  background_removal_client = Client("not-lain/background-removal")
23
 
 
24
  def remove_background(image):
25
- # Convert the PIL image to a byte stream
26
- img_bytes = BytesIO()
27
- image.save(img_bytes, format="PNG")
28
- img_bytes.seek(0)
29
-
30
- # Step 1: Remove background using the Gradio API
31
- result_url = background_removal_client.predict(
32
- f=img_bytes, # Pass the BytesIO object directly
33
- api_name="/png"
34
- )
 
 
 
 
 
 
35
 
36
- # Step 2: Download the image returned by the API
37
- response = requests.get(result_url)
38
- foreground = Image.open(BytesIO(response.content)).convert("RGBA")
39
 
40
- # Step 3: Apply `rmbg` for additional cleanup
41
- cleaned_foreground = remove(foreground)
42
 
43
- return cleaned_foreground.convert("RGB") # Directly return cleaned foregroun
 
 
 
44
 
45
  def process_image(image_path, depth_map_path=None):
46
  image_path = Path(image_path)
 
10
  from pathlib import Path
11
  import os
12
  import cv2
13
+ import tempfile
14
  from rembg import remove
15
  from gradio_client import Client
16
  import requests
 
22
  model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")
23
  background_removal_client = Client("not-lain/background-removal")
24
 
25
+
26
  def remove_background(image):
27
+ # Create a temporary file to save the image
28
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as temp_file:
29
+ # Convert the PIL image to a byte stream and save it to the temp file
30
+ image.save(temp_file, format="PNG")
31
+ temp_file_path = temp_file.name # Get the path of the temp file
32
+
33
+ try:
34
+ # Step 1: Remove background using the Gradio API
35
+ result_url = background_removal_client.predict(
36
+ f=temp_file_path, # Pass the path of the temporary file
37
+ api_name="/png"
38
+ )
39
+
40
+ # Step 2: Download the image returned by the API
41
+ response = requests.get(result_url)
42
+ foreground = Image.open(BytesIO(response.content)).convert("RGBA")
43
 
44
+ # Step 3: Apply `rmbg` for additional cleanup
45
+ cleaned_foreground = remove(foreground)
 
46
 
47
+ return cleaned_foreground.convert("RGB") # Directly return cleaned foreground
 
48
 
49
+ finally:
50
+ # Ensure the temporary file is deleted
51
+ if os.path.exists(temp_file_path):
52
+ os.remove(temp_file_path)
53
 
54
  def process_image(image_path, depth_map_path=None):
55
  image_path = Path(image_path)