Ximilar - Code snippets Python
Here you can find some useful code in Python that will help you with our API.
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
In this guide, we will look at how to extract (cut) an object from an image using the Ximilar Custom Object Detection Service. This is useful when you want to isolate detected objects for further processing or analysis.
The following example demonstrates how to use the Ximilar Python client to detect objects in an image and extract the first detected object using its bounding box.
- Name
DetectionClient
- Type
- class
- Description
The main client for interacting with the Ximilar 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]]