Skip to content

Commit 694b5ac

Browse files
committed
save segmented output
1 parent eb2af80 commit 694b5ac

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ sam2-coreml-python/
3434
python script.py
3535
```
3636

37-
The script will generate `output_mask.png` containing the segmentation mask.
37+
The script will generate `output_mask.png` containing the segmentation mask and `output_segmented.png` containing the segmented image.
3838

3939
## Models
4040

script.py

+20
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,20 @@ def save_mask(self, mask: np.ndarray, output_path: str):
165165
mask_image = (mask * 255).astype(np.uint8)
166166
cv2.imwrite(output_path, mask_image)
167167

168+
def apply_mask_to_image(self, image_path, mask):
169+
image = cv2.imread(image_path)
170+
mask_binary = mask.astype(np.uint8) * 255
171+
segmented = cv2.bitwise_and(image, image, mask=mask_binary)
172+
173+
# Create white background for transparency
174+
white_background = np.ones_like(image) * 255
175+
background = cv2.bitwise_and(
176+
white_background, white_background, mask=~mask_binary
177+
)
178+
# Combine segmented image with white background
179+
final_image = cv2.add(segmented, background)
180+
return final_image
181+
168182

169183
class PointSelector:
170184
def __init__(self, image_path, max_points=2):
@@ -300,7 +314,13 @@ def main():
300314
mask = sam.get_mask(original_size)
301315

302316
if mask is not None:
317+
# Save the mask
303318
sam.save_mask(mask, "output_mask.png")
319+
320+
# Save segmented image
321+
segmented_image = sam.apply_mask_to_image(image_path, mask)
322+
cv2.imwrite("output_segmented.png", segmented_image)
323+
304324
cv2.destroyAllWindows()
305325

306326
except Exception as e:

0 commit comments

Comments
 (0)