Skip to content

Smart Vision V2 Python 接口文档

Smart Vision V2 Python API

tip

To use Smart Vision SDK, first import the smartvisionsdk package:

from pysmartvision import smartvisionsdk

Python API Overview

ClassPublic Member FunctionsTypeDescription
Cameraopen(GetImageCB)functionOpen camera in parameterless mode
open(DeviceParam, GetImageCB)functionOpen camera with parameters
start_capture()functionStart streaming
stop_capture()functionStop streaming
close()functionClose camera
ImagedatastrPointer to buffer containing image data
wintTarget image width
hintTarget image height
cintNumber of image channels (typically 3)
lengthintMemory length occupied by image data
srcWidthintInternal image width, usually larger than final width
srcHeightintInternal image height
memCopyStartIndexintIndex indicating data in buffer
memCopyEndIndexintEnd index indicating data in buffer
planeOffsetintYUV data offset value
TcpConfigipstrIP address
portintPort number
SVSdkMemfdInfosrcYPlaneStrideintWidth of YUV data
srcSliceHeightintHeight of YUV data
memCopyStartIndexintStart index value (Note: Start index equals End index)
memCopyEndIndexintEnd index value
planeOffsetintYUV offset value
cam_idintCamera ID
MediaInfodurationintVideo duration
widthintVideo width
heightintVideo height
frame_rateintVideo frame rate
file_sizeintVideo file size
file_namestrVideo file name
Public FunctionDescription
set_log_level(SVLogLevel log_level)Set log level
set_log_destination(str destinationPath, bool also_to_stderr)Set log file name and path
log_to_stderr()Output logs to terminal. Once set, log files will not be saved. Generally not recommended.
GetImageCB(const Image, int)Used as input parameter for open() function to acquire image resources. This function is user-defined. The interface only provides type definition to standardize callback function definition.
set_off_mode()Set OFF mode to disable signal output.
int8_t get_tcp_setting(int cam_id, TcpConfig& tcp_setting)Get TCP settings.
int8_t tcp_send_signal(int cam_id, std::string message)Send TCP signal.
int8_t tcp_send(std::string message, TcpConfig& tcp_setting)Send TCP string message.
int8_t io_send(std::string io_str, std::string io_control_file)Write specified string to specific file.
int8_t send_signal_on(int device_id)Send up signal to specified device (e.g., do1, do2, do3), keeptime read from configuration.
int8_t send_signal_on(int device_id, int keeptime)Send up signal to specified device (e.g., do1, do2, do3), keeptime passed as parameter.
int8_t send_signal_off(int device_id)Send clear signal to specified device (e.g., do1, do2, do3).
string get_camera_info(int8_t idx = 0)Get corresponding configuration file path based on camera index, read and parse JSON format camera configuration.
string get_camera_default_setting(int8_t idx = 0)Load default configuration via camera index, get complete configuration string and sync to system singleton.
string get_sensor_model_info(int idx)Get sensor model information.
get_all_cam_ids(disable_cache=False)Decide whether to read from local configuration or detect all camera model names in real-time based on cache disabling.
vector<int> get_all_cam_index()Get all indices.
get_all_cameras(disable_cache=False)Call underlying detection logic to get all camera information.
int get_idx_by_loc_id(int loc_id)Find corresponding logical index (cam_id or idx) based on camera's physical location ID (loc_id).
int get_loc_id_by_idx(int idx)Reverse lookup physical location ID (loc_id) based on camera's logical index (idx).
int get_cam_index(std::string cam_id)Find corresponding logical index by camera name.
string get_cam_id(int cam_index)Find and return corresponding camera name based on logical index.
cv::Mat image_read(int8_t idx = 0)Safely read current preview frame from specified camera (JPEG format).
int8_t get_camera_status(int8_t idx = 0)Record and return current status code of specified camera index via logs.
void start_camera_capture(int idx = 0)Start image capture for specified camera.
void stop_camera_capture(int idx = 0)Stop image capture for specified camera.
int get_dst_width(int8_t idx = 0)Get target width of output image from specified camera.
int get_dst_height(int8_t idx = 0)Get target height of output image from specified camera.
int8_t notify_sve(SPhase phase_enum)Send current task phase notification to local SVE service via HTTP (POST) request.
int8_t save_result(const char *release_id, const char *release_version, const char *origin_file, const char *mask_file, const char *final_file, const char *additional = "")Package image analysis task result file paths and additional information as JSON and report to local SVE service.
get_cvimage(img, idx, max_timeout_ms)Get image data from specified index, convert to image object directly usable by Python.
void qmm_cleanup(int cam_id = 0)Send control signal in specific format to stop specified or all camera services.
void qmm_cleanup_all()Send control signal in specific format to stop specified or all camera services.
void qmm_cleanup_invalid()Clean up qmm processes with abnormal status.
int qmm_status(int idx = 0)Check if service process corresponding to specified camera index is alive, implemented based on Redis heartbeat mechanism.
int start_record(int idx)Safely start camera video recording with multiple pre-checks.
get_record_status()Query current video recording status.
MediaInfo stop_record(int idx)Stop camera recording process and extract recording result metadata from internal state.
int set_bpp_binning(std::string cam_id, int binning_flag, int hb, int vb, int bpp_flag, int bpp)Specify camera pixel binning and bit depth.
EnumMember VariableTypeDescription
SVLogLevelSINFOintLog level SINFO
SWARNINGintLog level SWARNING
SERRORintLog level SERROR
SDEBUGintLog level SDEBUG
SOFFuint8_tLog level SOFF
SignalTypeOFFintDisable signal output
NG_SIGNALuint8_tNG signal output mode
ALARM_SIGNALuint8_tAlarm signal output mode
OK_SIGNALuint8_tOK signal output mode
SignalModeIO_MODEuint8_tIO mode
TCP_MODEuint8_tTCP mode
MODBUS_MODEuint8_tMODBUS mode
UART_MODEuint8_tUART mode

Camera Class

Operations related to instantiating Camera objects. Camera operations such as opening and capturing images are all based on instantiated Camera objects.

tip

This version is compatible with the first generation camera's open function open, start capture function start_capture, stop capture function stop_capture, and close camera function close.

For the latest functions:

warning

Unlike C++, Python code does not require namespace import. Instead, import the smartvisionsdk module using:

from pysmartvision import smartvisionsdk

See the following interfaces for specific usage.

Open Camera in Parameterless Mode

Parameterless mode: Use default camera parameter configuration

APIopen(cb)
DescriptionOpen camera in parameterless mode.
ParametersInput parameter is a callback function. Callback function is user-defined. See Callback Function GetImageCB for details.
Return Value0: Success. -1: Failure.

Example (camera_instance is an instance of Camera class, same below):

python
# Open camera in parameterless mode
camera_instance = smartvisionsdk.Camera()
res = camera_instance.open(my_get_img_cb)

Open Camera with Parameters

Parameter mode: Use custom parameter configuration, see DeviceParam

APIopen(dev_param, cb)
DescriptionOpen camera with parameters.
Parametersdev_param: Instance of DeviceParam class. cb: Callback function. Callback function is user-defined. See Callback Function GetImageCB for details.
Return Value0: Success. -1: Failure.

Example:

python
# Open camera with parameters
camera_instance = smartvisionsdk.Camera()
res = camera_instance.open(device_param, my_get_img_cb)

Start Streaming

APIstart_capture()
DescriptionStart streaming
ParametersNone
Return ValueNone

Example:

python
# Start streaming
camera_instance.start_capture()

Stop Streaming

APIstop_capture()
DescriptionStop streaming
ParametersNone
Return ValueNone

Example:

python
# Stop streaming
camera_instance.stop_capture()

Close Camera

APIclose()
DescriptionClose camera
ParametersNone
Return Value0: Success. -1: Failure.

Example:

python
# Close camera
res = camera_instance.close()

DeviceParam Class

Defines parameter configuration file path with path. This configuration file is used to configure camera parameters. Therefore, it is only used when opening camera with parameters.

Member VariableTypeDefaultDescription
cfg_namestrPath to parameter configuration file

Set DeviceParam Configuration File

APIset_cfgname(config_file)
DescriptionSet path to parameter configuration file. This interface sets the cfg_name variable.
Parametersconfig_file: Camera parameter configuration file
Return ValueNone

Example:

python
# Set configuration file
device_param = smartvisionsdk.DeviceParam()
device_param.set_cfgname("./config.json")

Image Class

Defines image data related information, including image configuration and pointer variables.

Member VariableTypeDefaultDescription
datastrString pointer to buffer containing data
wintTarget image width
hintTarget image height
cintNumber of image channels (typically 3)
lengthintMemory length occupied by image data
srcWidthintInternal image width, usually larger than final width
srcHeightintInternal image height
memCopyStartIndexintIndex indicating data in buffer
memCopyEndIndexintEnd index indicating data in buffer
planeOffsetintYUV data offset value

TcpConfig Class

Defines TCP signal output configuration.

Member VariableTypeDefaultDescription
ipstrIP address
portintPort number

SVSdkMemfdInfo Class

Defines data buffer information.

Member VariableTypeDefaultDescription
srcYPlaneStrideintWidth of YUV data
srcSliceHeightintHeight of YUV data
memCopyStartIndexintStart index value (Note: Start index equals End index)
memCopyEndIndexintEnd index value
planeOffsetintYUV offset value
cam_idintCamera ID

Set Log Level (Function set_log_level)

APIset_log_level(log_level)
DescriptionSet log level.
Parameterslog_level: SVLogLevel enum. See SVLogLevel Enum for details.
Return ValueNone

Example:

python
# Set log level
smartvisionsdk.set_log_level(smartvisionsdk.SVLogLevel.SINFO)

Set Log File Name and Path (Function set_log_destination)

APIset_log_destination(destinationPath, also_to_stderr)
DescriptionSet log file name and path
ParametersdestinationPath: Log file path, default is "./aidclog_smart_vision_". also_to_stderr: Whether to output to terminal, default is False
Return ValueNone

Example:

python
# Set log file name and path
log_path = "./aidclog_smart_vision_setting_"
smartvisionsdk.set_log_destination(log_path, False)

Output Logs to Terminal (Function log_to_stderr)

APIlog_to_stderr()
DescriptionOutput logs to terminal. Once set, log files will not be saved. Generally not recommended.
ParametersNone
Return ValueNone

Example:

python
# Output logs to terminal
smartvisionsdk.log_to_stderr()

Log Level (Enum SVLogLevel)

Member VariableTypeDefaultDescription
SINFOint0Log level SINFO
SWARNINGintLog level SWARNING
SERRORintLog level SERROR
SDEBUGintLog level SDEBUG
SOFFintLog level SOFF

Callback Function GetImageCB

APIGetImageCB(image, mem_info)
DescriptionUsed as input parameter for open() function to acquire image resources. This function is user-defined. The interface only provides type definition to standardize callback function definition.
ParametersFirst parameter is Image class instance through which data is passed. Second parameter is SVSdkMemfdInfo class instance containing buffer index, YUV data width/height, etc.
Return ValueUser-defined

Example:

python
# Callback function definition
def my_get_img_cb(cap_img, mem_info):
    # Process image data
    print(f"Image width: {cap_img.w}, height: {cap_img.h}")
    return 0

Set OFF Mode to Disable Signal Output (Function set_off_mode)

APIset_off_mode()
DescriptionSet OFF mode to disable signal output.
ParametersNone
Return Value-1: Failure. 0: Success.

Example:

python
# Set OFF mode to disable signal output
res = smartvisionsdk.set_off_mode()

Get Camera Configuration (Function get_camera_info)

APIget_camera_info(idx)
DescriptionGet corresponding configuration file path based on camera index, read and parse JSON format camera configuration.
Parametersidx: Camera index.
Return ValueSuccess: JSON format string containing camera configuration. Failure: Empty string ("").

Example:

python
info = smartvisionsdk.get_camera_info(0)

Get Complete Configuration (Function get_camera_default_setting)

APIget_camera_default_setting(idx)
DescriptionLoad default configuration via camera index, get complete configuration string and sync to system singleton.
Parametersidx: Camera index.
Return ValueSuccess: JSON format string containing camera configuration. Failure: Empty string ("").

Example:

python
setting = smartvisionsdk.get_camera_default_setting(0)

Get Sensor Model Information (Function get_sensor_model_info)

APIget_sensor_model_info(idx)
DescriptionGet sensor model information.
Parametersidx: Camera index.
Return ValueSuccess: String containing sensor model information. Failure: Empty string ("").

Example:

python
model_info = smartvisionsdk.get_sensor_model_info(0)

Get All Camera IDs (Function get_all_cam_ids)

APIget_all_cam_ids(disable_cache)
DescriptionDecide whether to read from local configuration or detect all camera model names in real-time based on cache disabling.
Parametersdisable_cache (True: Force re-detection, clear cache. False: Use cached data, no re-detection).
Return ValueList of SensorName strings for all successfully identified cameras.

Example:

python
# Use cache
camera_list = smartvisionsdk.get_all_cam_ids(False)

Get All Camera Information (Function get_all_cameras)

APIget_all_cameras(disable_cache)
DescriptionCall underlying detection logic to get all camera information.
Parametersdisable_cache (True: Force re-detection, clear cache. False: Use cached data, no re-detection).
Return ValueDictionary where key is camera physical location ID (e.g., 0, 1, 2) and value is corresponding sensor name.

Example:

python
# Use cache
cameras = smartvisionsdk.get_all_cameras(False)

Get SDK Version Information (Function get_build_version)

APIget_build_version()
DescriptionGet SDK version information.
ParametersNone
Return ValueSDK version string

Example:

python
# Get SDK version information
res = smartvisionsdk.get_build_version()

Get Mat Object Data (Function get_cvimage)

APIget_cvimage(img, idx, max_timeout_ms)
DescriptionGet image data from specified index, convert to image object directly usable by Python.
Parametersimg: Image object. idx: Camera logical index. max_timeout_ms: Maximum wait time in milliseconds.
Return ValueConverted image object

Example:

python
# Get Mat object data, where cap_img is input image object containing YUV data
im = smartvisionsdk.get_cvimage(cap_img, 0, 1000)

Get Latest Log Message (Function log_last_msg)

APIlog_last_msg(log_level)
DescriptionGet latest log message
ParametersSVLogLevel log level
Return ValueLatest log record

Example:

python
# Get latest log message
res = smartvisionsdk.log_last_msg(log_level)

Get FPS (Function get_fps)

APIget_fps(idx)
DescriptionGet real-time FPS from callback function, which represents camera capture frame rate.
ParametersCamera index idx. MIPI camera: 0~2. Default is 0.
Return ValueFPS value

Example:

python
# Get real-time camera capture FPS
fps_v = smartvisionsdk.get_fps()

Configure Camera (Function configure_camera)

APIconfigure_camera(file_path, set_property, validation)
DescriptionSet camera parameters.
Parametersfile_path: Configuration file. set_property: Apply immediately (True: yes, False: no). validation: Validate parameters (True: yes, False: no)
Return Value0: Success. -1: Failure

Example:

python
# Configure camera parameters
res = smartvisionsdk.configure_camera("./param.json", True, True)

Start Image Capture (Function start_camera_capture)

APIstart_camera_capture(idx)
DescriptionStart image capture for specified camera.
Parametersidx: Camera logical index.
Return ValueNone

Example:

python
smartvisionsdk.start_camera_capture(0)

Stop Image Capture (Function stop_camera_capture)

APIstop_camera_capture(idx)
DescriptionStop image capture for specified camera.
Parametersidx: Camera logical index.
Return ValueNone

Example:

python
smartvisionsdk.stop_camera_capture(0)

Close Camera Service (Function qmm_cleanup)

APIqmm_cleanup(cam_id)
DescriptionSend control signal in specific format to stop specified camera service.
Parameterscam_id: Camera logical index.
Return ValueNone

Example:

python
# Stop camera 0
smartvisionsdk.qmm_cleanup(0)

Close All Camera Services (Function qmm_cleanup_all)

APIqmm_cleanup_all()
DescriptionSend control signal in specific format to stop all camera services.
ParametersNone
Return ValueNone

Example:

python
smartvisionsdk.qmm_cleanup_all()

Process Check (Function qmm_status)

APIqmm_status(idx)
DescriptionCheck if service process corresponding to specified camera index is alive, implemented based on Redis heartbeat mechanism.
Parametersidx: Camera logical index.
Return Value2: Service running. 0: Not registered. 4: Service abnormal.

Example:

python
status = smartvisionsdk.qmm_status(0)

Start Recording (Function start_record)

APIstart_record(idx)
DescriptionSafely start camera video recording with multiple pre-checks.
Parametersidx: Camera logical index.
Return Value0: Success. -1: Failure.

Example:

python
cam_idx = 0
if smartvisionsdk.get_camera_status(cam_idx) == 2:
    ret = smartvisionsdk.start_record(cam_idx)
    if ret == 0:
        print("Started successfully!")
    else:
        print("Failed to start recording")

Recording Status Check (Function get_record_status)

APIget_record_status()
DescriptionQuery current video recording status.
ParametersNone
Return Value0: Recording. -1: Not recording.

Example:

python
record_status = smartvisionsdk.get_record_status()
if record_status == 0:
    print("Recording video...")
else:
    print("Not recording")

Stop Recording (Function stop_record)

APIstop_record(idx)
DescriptionStop camera recording process and extract recording result metadata from internal state.
Parametersidx: Camera logical index.
Return ValueMediaInfo object containing recording result information.

Example:

python
cam_idx = 0
# Stop recording and get information
record_info = smartvisionsdk.stop_record(cam_idx)

Signal Type Definition (Enum SignalType)

Member VariableTypeDefaultDescription
OFFint0Disable signal output
NG_SIGNALuint8_tNG signal output mode
ALARM_SIGNALuint8_tAlarm signal output mode
OK_SIGNALuint8_tOK signal output mode

Signal Mode Definition (Enum SignalMode)

Member VariableTypeDefaultDescription
IO_MODEuint8_t0IO mode
TCP_MODEuint8_t1TCP mode
MODBUS_MODEuint8_t2MODBUS mode
UART_MODEuint8_t3UART mode