codic commited on
Commit
4fd66ca
·
verified ·
1 Parent(s): a75e3aa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +65 -59
app.py CHANGED
@@ -14,71 +14,77 @@ feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
14
  model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")
15
 
16
  def process_image(image_path, depth_map_path=None):
17
- image_path = Path(image_path)
18
- image_raw = Image.open(image_path)
19
- image = image_raw.resize(
20
- (1600, int(1600 * image_raw.size[1] / image_raw.size[0])),
21
- Image.Resampling.LANCZOS,
22
- )
23
-
24
- # Step 1: Separate the main subject
25
- image_np = np.array(image)
26
- subject = remove(image_np) # Removes background
27
-
28
- # Ensure subject is in RGB format
29
- if len(subject.shape) == 2 or subject.shape[2] != 3:
30
- if subject.shape[2] == 4: # If the image has 4 channels (RGBA)
31
- subject = cv2.cvtColor(subject, cv2.COLOR_RGBA2RGB)
32
- else:
33
- subject = cv2.cvtColor(subject, cv2.COLOR_GRAY2RGB) # Ensure it's RGB if grayscale
34
-
35
- # Step 2: Inpaint the background
36
- mask = cv2.inRange(subject, (0, 0, 0), (0, 0, 0)) # Binary mask
37
- background_inpainted = cv2.inpaint(image_np, mask, inpaintRadius=3, flags=cv2.INPAINT_TELEA)
38
-
39
- # Convert back to PIL format
40
- subject_image = Image.fromarray(subject)
41
- inpainted_bg_image = Image.fromarray(background_inpainted)
42
-
43
- # Step 3: Generate or use existing depth map
44
- if depth_map_path:
45
- # Check if the depth map path is a .npy file or an image
46
- if depth_map_path.endswith('.npy'):
47
- # Load the depth map from a .npy file
48
- depth_image = np.load(depth_map_path)
49
- # Normalize and invert depth map
50
- depth_image = 255 - (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image)) * 255
51
- depth_image = depth_image.astype('uint8')
52
- else:
53
- # Resize user-provided depth map to match RGB size
54
- depth_image_raw = Image.open(depth_map_path)
55
- depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
56
- depth_image = np.array(depth_image)
57
- # Normalize depth image
58
- depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
59
- depth_image = (depth_image * 255).astype('uint8')
60
- else:
61
- # Generate depth map using the model
62
- encoding = feature_extractor(image, return_tensors="pt")
63
- with torch.no_grad():
64
- outputs = model(**encoding)
65
- predicted_depth = outputs.predicted_depth
66
- prediction = torch.nn.functional.interpolate(
67
- predicted_depth.unsqueeze(1),
68
- size=image.size[::-1],
69
- mode="bicubic",
70
- align_corners=False,
71
- ).squeeze()
72
- depth_image = (prediction.cpu().numpy() * 255 / np.max(prediction.cpu().numpy())).astype("uint8")
73
-
74
- # Step 4: Apply depth to main subject only
75
  try:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
  gltf_path = create_3d_obj(np.array(subject_image), depth_image, image_path)
77
  img = Image.fromarray(depth_image)
 
78
  return [img, gltf_path, gltf_path]
79
  except Exception as e:
80
  print("Error reconstructing 3D model:", e)
81
- raise Exception("Error reconstructing 3D model")
82
 
83
  def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
84
  # Your existing create_3d_obj implementation...
 
14
  model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")
15
 
16
  def process_image(image_path, depth_map_path=None):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  try:
18
+ image_path = Path(image_path)
19
+ image_raw = Image.open(image_path)
20
+ image = image_raw.resize(
21
+ (1600, int(1600 * image_raw.size[1] / image_raw.size[0])),
22
+ Image.Resampling.LANCZOS,
23
+ )
24
+
25
+ # Step 1: Separate the main subject
26
+ print("Removing background...")
27
+ image_np = np.array(image)
28
+ subject = remove(image_np) # Removes background
29
+
30
+ # Ensure subject is in RGB format
31
+ if len(subject.shape) == 2 or subject.shape[2] != 3:
32
+ if subject.shape[2] == 4: # If the image has 4 channels (RGBA)
33
+ subject = cv2.cvtColor(subject, cv2.COLOR_RGBA2RGB)
34
+ else:
35
+ subject = cv2.cvtColor(subject, cv2.COLOR_GRAY2RGB) # Ensure it's RGB if grayscale
36
+
37
+ # Step 2: Inpaint the background
38
+ print("Inpainting background...")
39
+ mask = cv2.inRange(subject, (0, 0, 0), (0, 0, 0)) # Binary mask
40
+ background_inpainted = cv2.inpaint(image_np, mask, inpaintRadius=3, flags=cv2.INPAINT_TELEA)
41
+
42
+ # Convert back to PIL format
43
+ subject_image = Image.fromarray(subject)
44
+ inpainted_bg_image = Image.fromarray(background_inpainted)
45
+
46
+ # Step 3: Generate or use existing depth map
47
+ if depth_map_path:
48
+ print("Loading depth map...")
49
+ # Check if the depth map path is a .npy file or an image
50
+ if depth_map_path.endswith('.npy'):
51
+ # Load the depth map from a .npy file
52
+ depth_image = np.load(depth_map_path)
53
+ # Normalize and invert depth map
54
+ depth_image = 255 - (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image)) * 255
55
+ depth_image = depth_image.astype('uint8')
56
+ else:
57
+ # Resize user-provided depth map to match RGB size
58
+ depth_image_raw = Image.open(depth_map_path)
59
+ depth_image = depth_image_raw.resize(image.size, Image.Resampling.NEAREST)
60
+ depth_image = np.array(depth_image)
61
+ # Normalize depth image
62
+ depth_image = (depth_image - np.min(depth_image)) / (np.max(depth_image) - np.min(depth_image))
63
+ depth_image = (depth_image * 255).astype('uint8')
64
+ else:
65
+ print("Generating depth map using the model...")
66
+ # Generate depth map using the model
67
+ encoding = feature_extractor(image, return_tensors="pt")
68
+ with torch.no_grad():
69
+ outputs = model(**encoding)
70
+ predicted_depth = outputs.predicted_depth
71
+ prediction = torch.nn.functional.interpolate(
72
+ predicted_depth.unsqueeze(1),
73
+ size=image.size[::-1],
74
+ mode="bicubic",
75
+ align_corners=False,
76
+ ).squeeze()
77
+ depth_image = (prediction.cpu().numpy() * 255 / np.max(prediction.cpu().numpy())).astype("uint8")
78
+
79
+ # Step 4: Apply depth to main subject only
80
+ print("Creating 3D object...")
81
  gltf_path = create_3d_obj(np.array(subject_image), depth_image, image_path)
82
  img = Image.fromarray(depth_image)
83
+ print("3D model reconstruction successful.")
84
  return [img, gltf_path, gltf_path]
85
  except Exception as e:
86
  print("Error reconstructing 3D model:", e)
87
+ raise Exception("Error reconstructing 3D model") from e
88
 
89
  def create_3d_obj(rgb_image, depth_image, image_path, depth=12):
90
  # Your existing create_3d_obj implementation...