File size: 2,954 Bytes
647f69c
 
 
 
 
 
 
 
 
 
 
 
 
 
b2e88b8
647f69c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
#!/usr/bin/env python3
"""
SAM3 API Usage Example

This example shows how to use the SAM3 text-prompted segmentation API
for road defect detection.
"""
import requests
import base64
from PIL import Image
import io
import os

# Configuration
ENDPOINT_URL = "https://p6irm2x7y9mwp4l4.us-east-1.aws.endpoints.huggingface.cloud"

def segment_image(image_path, classes):
    """
    Segment objects in an image using text prompts

    Args:
        image_path: Path to the image file
        classes: List of object classes to segment (e.g., ["pothole", "crack"])

    Returns:
        List of dictionaries with 'label', 'mask' (base64), and 'score'
    """
    # Load and encode image
    with open(image_path, "rb") as f:
        image_b64 = base64.b64encode(f.read()).decode()

    # Make API request
    response = requests.post(
        ENDPOINT_URL,
        json={
            "inputs": image_b64,
            "parameters": {
                "classes": classes
            }
        },
        timeout=30
    )

    response.raise_for_status()
    return response.json()

def save_masks(results, output_dir="output"):
    """
    Save segmentation masks as PNG files

    Args:
        results: API response (list of dictionaries)
        output_dir: Directory to save masks
    """
    os.makedirs(output_dir, exist_ok=True)

    for result in results:
        label = result["label"]
        score = result["score"]
        mask_b64 = result["mask"]

        # Decode mask
        mask_bytes = base64.b64decode(mask_b64)
        mask_image = Image.open(io.BytesIO(mask_bytes))

        # Save mask
        output_path = os.path.join(output_dir, f"mask_{label}.png")
        mask_image.save(output_path)

        print(f"✓ Saved {label} mask: {output_path} (score: {score:.2f})")

def main():
    """Example: Road defect detection"""

    # Example 1: Detect road defects
    print("Example 1: Road Defect Detection")
    print("=" * 50)

    image_path = "../test_images/test.jpg"
    classes = ["pothole", "crack", "patch", "debris"]

    print(f"Image: {image_path}")
    print(f"Classes: {classes}")
    print()

    try:
        results = segment_image(image_path, classes)
        print(f"Found {len(results)} segmentation masks")
        print()

        save_masks(results, output_dir="defects_output")
        print()

    except requests.exceptions.RequestException as e:
        print(f"Error: {e}")
        return

    # Example 2: Segment specific objects
    print("\nExample 2: Specific Object Segmentation")
    print("=" * 50)

    classes = ["asphalt", "yellow line"]

    print(f"Classes: {classes}")
    print()

    try:
        results = segment_image(image_path, classes)
        print(f"Found {len(results)} segmentation masks")
        print()

        save_masks(results, output_dir="objects_output")

    except requests.exceptions.RequestException as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    main()