File size: 2,864 Bytes
72f5484 |
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 |
"""
Example script for using the Transparent Background Remover Inference Endpoint.
This script:
- Loads three sample images (sample1.png, sample2.png, sample3.png)
- Encodes them as base64 data URIs
- Builds a JSON payload and sends a POST request to the endpoint
- Receives the processed images (base64-encoded) and saves them as PNG files
Requirements:
- Python 3.10+
- requests
Usage:
python example.py
"""
import requests
import base64
def encode_image_to_base64(filename):
"""
Encode an image file to a base64 data URI.
Args:
filename (str): Path to the image file.
Returns:
str: Base64-encoded string with data URI prefix.
"""
with open(filename, "rb") as f:
image_bytes = f.read()
encoded = base64.b64encode(image_bytes).decode("utf-8")
# Assuming PNG format; adjust MIME type if using another format.
data_uri = f"data:image/png;base64,{encoded}"
return data_uri
def save_base64_to_file(data_uri, output_filename):
"""
Decode a base64 data URI and save it as an image file.
Args:
data_uri (str): The data URI containing the base64-encoded image.
output_filename (str): The output filename to save the image.
"""
header, encoded = data_uri.split(",", 1)
image_data = base64.b64decode(encoded)
with open(output_filename, "wb") as f:
f.write(image_data)
print(f"Saved {output_filename}")
def main():
# Replace with your actual endpoint URL and API token (if required)
endpoint_url = "https://endpoints.huggingface.co/your-endpoint-url"
headers = {
"Authorization": "Bearer YOUR_API_TOKEN",
"Content-Type": "application/json"
}
# Encode three sample images.
sample_images = [
encode_image_to_base64("bear1.png"),
encode_image_to_base64("bear2.png"),
encode_image_to_base64("bear3.png")
]
# Build the payload according to the handler's expected format.
payload = {
"inputs": {
"images": sample_images,
"output_type": "rgba", # Choose "rgba", "map", "green", "blur", or "overlay"
"threshold": 0.1,
"reverse": False # Set to True if you want to remove the foreground instead
}
}
print("Sending request to endpoint...")
response = requests.post(endpoint_url, json=payload, headers=headers)
if response.status_code != 200:
print("Error:", response.status_code, response.text)
return
result = response.json()
print("Processing Times:\n", result.get("processing_times", "No timing info provided."))
# Save each processed image to a file.
images = result.get("images", [])
for idx, data_uri in enumerate(images):
save_base64_to_file(data_uri, f"output_{idx+1}.png")
if __name__ == "__main__":
main()
|