Views
No views yet
handler.pyrequirements.txt1# Install dependencies
2pip install -r requirements.txt
3
4# Run local tests
5python test_handler.py1import requests
2import base64
3from PIL import Image
4import io
5
6# Load and encode your image
7image = Image.open("your_image.jpg")
8buffered = io.BytesIO()
9image.save(buffered, format="JPEG")
10img_base64 = base64.b64encode(buffered.getvalue()).decode()
11
12# Prepare the request
13data = {
14 "inputs": img_base64, # Base64 encoded image
15 "points": [[[[x1, y1], [x2, y2]]]], # Point coordinates
16 "labels": [[[1, 1]]] # 1 for positive (foreground), 0 for negative (background)
17}
18
19# Send request to your endpoint
20response = requests.post(
21 "https://YOUR-ENDPOINT-URL.endpoints.huggingface.cloud",
22 json=data,
23 headers={"Authorization": "Bearer YOUR_HF_TOKEN"}
24)
25
26result = response.json()[[[[x1, y1], [x2, y2], ...]]][image_dim, object_dim, points_per_object_dim, coordinates][[[1, 1, ...]]][image_dim, object_dim, point_labels]1 = positive click (foreground), 0 = negative click (background)1[
2 {
3 "masks": [[[...]]],
4 "shape": [1, 3, 1200, 1800],
5 "num_masks": 3,
6 "description": "Generated 3 masks ranked by quality score"
7 }
8]masks[0] = Best quality mask (use this one in most cases)masks[1] = Second bestmasks[2] = Third best[num_objects, num_masks_per_object, height, width]True indicates the segmented region1data = {
2 "inputs": "<base64_encoded_image>",
3 "points": [[[[500, 375], [1000, 500]]]], # Two points on the object
4 "labels": [[[1, 1]]] # Both positive (foreground)
5}1data = {
2 "inputs": "<base64_encoded_image>",
3 "points": [[[[500, 375], [1000, 500], [200, 200]]]],
4 "labels": [[[1, 1, 0]]] # Two positive, one negative (background)
5}1data = {
2 "inputs": "<base64_encoded_image>",
3 "points": [[
4 [[500, 375]], # Points for object 1
5 [[1000, 500]] # Points for object 2
6 ]],
7 "labels": [[
8 [1], # Label for object 1
9 [1] # Label for object 2
10 ]]
11}1import numpy as np
2from PIL import Image
3
4# Get the best quality mask (first one)
5mask = np.array(result[0]["masks"])[0, 0] # [object_0, best_mask]
6
7# Convert to PIL Image
8mask_image = Image.fromarray((mask * 255).astype(np.uint8))
9
10# Apply mask to original image
11masked_image = np.array(original_image) * mask[:, :, np.newaxis]
12masked_pil = Image.fromarray(masked_image.astype(np.uint8))1result = response.json()
2
3if "error" in result[0]:
4 print(f"Error: {result[0]['error']}")
5 print(f"Type: {result[0]['type']}")
6else:
7 masks = result[0]["masks"]
8 # Process masks...transformers>=4.40.0torch>=2.0.0pillow>=9.0.0numpy>=1.21.0[[[[x, y]]]][[[1]]]