Ximilar – Code Snippets in Python
This page contains several code snippets in Python to help you work with the Ximilar API effectively.
Loading base64 Image Data
import base64, requests, json
with open(__IMAGE_PATH__, "rb") as image_file:
encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
data = {"records": [{"_base64": encoded_string}]}
response = requests.post(endpoint, headers=headers, data=json.dumps(data))
Extracting Object From Detection API
This example demonstrates how to use the Ximilar Custom Object Detection service and Python client to detect objects in an image and extract (crop) the first object (the most confident one) using its bounding box. This is useful for isolating objects for further processing or analysis.
- Name
DetectionClient
- Type
- class
- Description
The main client for interacting with the Ximilar object detection API.
- Name
get_task
- Type
- method
- Description
Retrieves a specific detection task by its ID.
- Name
detect
- Type
- method
- Description
Runs the detection task on the provided image(s) and returns detection results.
- Name
bound_box
- Type
- list
- Description
The bounding box of the detected object in the format
[x_min, y_min, x_max, y_max]
.
Extracting object from detection API
from ximilar.client import DetectionClient
import cv2
# get Detection Task
client = DetectionClient("__API_TOKEN__")
detection_task, status = client.get_task("__DETECTION_TASK_ID__")
# Getting Detection Result:
result = detection_task.detect([{"_file": "__LOCAL_PATH__", "noresize": True}])
image = cv2.imread("__LOCAL_PATH__")
bbox = result["record"]["_objects"][0]["bound_box"]
first_object = image[bbox[1] : bbox[3], bbox[0] : bbox[2]]