Spaces:
Runtime error
Runtime error
Create depth_segmentation.py
Browse files- depth_segmentation.py +43 -0
depth_segmentation.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import cv2
|
| 2 |
+
import numpy as np
|
| 3 |
+
from PIL import Image
|
| 4 |
+
|
| 5 |
+
def segment_image_by_depth(original_img_path, depth_map_path, num_segments=3):
|
| 6 |
+
# Load original image (JPG) and depth map
|
| 7 |
+
original_img = Image.open(original_img_path).convert("RGB") # Convert to RGB
|
| 8 |
+
depth_map = cv2.imread(depth_map_path, cv2.IMREAD_GRAYSCALE)
|
| 9 |
+
|
| 10 |
+
# Normalize depth map
|
| 11 |
+
depth_map = cv2.normalize(depth_map, None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8)
|
| 12 |
+
|
| 13 |
+
# Calculate depth ranges based on the number of segments
|
| 14 |
+
segment_ranges = np.linspace(0, 255, num_segments + 1).astype(int)
|
| 15 |
+
|
| 16 |
+
segmented_images = []
|
| 17 |
+
|
| 18 |
+
for i in range(num_segments):
|
| 19 |
+
# Generate mask for the current depth range
|
| 20 |
+
lower, upper = int(segment_ranges[i]), int(segment_ranges[i + 1])
|
| 21 |
+
mask = cv2.inRange(depth_map, lower, upper)
|
| 22 |
+
|
| 23 |
+
# Convert mask to 3 channels to match the original image
|
| 24 |
+
mask_rgb = cv2.merge([mask, mask, mask])
|
| 25 |
+
|
| 26 |
+
# Apply mask to the original image
|
| 27 |
+
segmented_img = cv2.bitwise_and(np.array(original_img), mask_rgb)
|
| 28 |
+
|
| 29 |
+
# Convert back to PIL Image and add an alpha channel
|
| 30 |
+
segmented_img_pil = Image.fromarray(segmented_img).convert("RGBA")
|
| 31 |
+
alpha_channel = Image.fromarray(mask).convert("L") # Use the mask as the alpha channel
|
| 32 |
+
segmented_img_pil.putalpha(alpha_channel) # Add transparency based on depth mask
|
| 33 |
+
|
| 34 |
+
segmented_images.append(segmented_img_pil)
|
| 35 |
+
|
| 36 |
+
# Save each segmented image as PNG
|
| 37 |
+
output_paths = []
|
| 38 |
+
for idx, seg_img in enumerate(segmented_images):
|
| 39 |
+
output_path = f"outputs/segment_{idx + 1}.png"
|
| 40 |
+
seg_img.save(output_path)
|
| 41 |
+
output_paths.append(output_path)
|
| 42 |
+
|
| 43 |
+
return output_paths
|