Evo 7.12.0-TM26061101
Evo LPR Engine
Loading...
Searching...
No Matches
Python

Pythone APIs.

To use the engines, import 'PyEvo.py' module. For its path, refer to SDK contents.

Example for Snapshot Engine

import ctypes
import glob
import PyEvo
#=====================================================
#
#
#
#=====================================================
def get_img_data(fpath):
import PIL.Image
pf = -1 # Pixel-Format of image
pil_img = PIL.Image.open(fpath) # Load source image file.
#
# Refer to the following for pixel modes supported by 'PIL' package.
#
# https://pillow.readthedocs.io/en/3.1.x/handbook/concepts.html#concept-modes
#
#
# For details of Evo's supported pixel formats, refer to developer documents.
#
# In case of 8Bit gray
if pil_img.mode == 'L':
pf = 0
# In case of YCbCr 4:2:2 as 'YUY2'
elif pil_img.mode == 'YCbCr':
pf = 10
# In case of 24Bit RGB as 'BGR'
elif pil_img.mode == 'RGB':
pf = 20
else:
# Other packed formats and all the planar formats
# are not covered in this example.
raise RuntimeError('Unsupported Pixel Formats')
# Create image object.
img = PyEvo.Image()
# Set to the address of the image data.
img.planes[0] = ctypes.cast(ctypes.c_char_p(pil_img.tobytes()), ctypes.c_void_p)
# Set to width of the image data by the pixel.
img.width = pil_img.width
# Set to height of the image data by the pixel.
img.height = pil_img.height
# Set to pixel format of the image data.
img.pf = pf
# Set to stride of the image data.
# If less than or equal to zero, calculated automatically by Evo engine.
img.strides[0] = 0
return img
#=====================================================
#
#
#
#=====================================================
def get_enc_img(fpath):
encimg = bytes()
try:
f = open(fpath, 'rb')
encimg = f.read()
except:
print("Opening the file '{}'".format(fpath))
return encimg
#=====================================================
#
#
#
#=====================================================
def lpd_judge_cb(img_size, rects, confidences, num, results):
'''
Arguments
img_size : Array of 'PyEvo.Rect' type.
There is only one element which describes size of the input image.
rects : Array of 'PyEvo.Rect' type.
Describe bounding boxes of all the detected license plates.
confidences : Array of float type.
Describe confidences of all the detected license plates.
Ranges of the values are between 0 and 100.
num : Single value of int type.
Total number of detected license plates.
results : Array of int type.
Determine whether each detected license plate is correct (0: incorrect, 1: correct).
By default, all the elements are 0s.
'''
img_sz = img_size[0] # Only sinlge element is valid.
print("")
# Print size of the input image.
fmtstr = "Image Size : Width({}), Height({})";
print(fmtstr.format(img_sz.width, img_sz.height))
# Print count of the detections.
fmtstr = "Detection Count: {}";
print(fmtstr.format(num))
print("")
for i in range(num):
# Print index of the detection.
print(" Index : {}".format(i))
# Print bounding-box of the detection.
# Note the detected bounding-box can be different from the recognized one.
fmtstr = " Bounding Box: x({}), y({}), width({}), height({})";
print(fmtstr.format(rects[i].x, rects[i].y, rects[i].width, rects[i].height))
# Print confidence of the detection.
print(" Confidence : {:.2f}%".format(confidences[i]))
print("--------------------------------------------")
if lpd_judge_cb.judgement_type == "the best":
# [+]
best = -1
maxarea = 0
for i in range(num):
area = rects[i].width * rects[i].height;
if (area > maxarea) and (confidences[i] >= lpd_judge_cb.min_confidence):
maxarea = area
best = i
if best >= 0: results[best] = 1
# [-]
elif lpd_judge_cb.judgement_type == "all":
for i in range(num): results[i] = 1
else:
pass # Ignore all the detected license plates.
return 0
#=====================================================
#
#
#
#=====================================================
def print_lpi(lpi):
result = lpi.gather()
fmtstr = "String : '{}'\n"
fmtstr += "Position: x({}), y({}), width({}), height({})\n"
fmtstr += "LP-Type : {} ({:.2f}%)"
for info in result:
output = fmtstr.format(info['string'],
info['position'].x,
info['position'].y,
info['position'].width,
info['position'].height,
info['lp_type'],
info['lp_conf'])
print(output)
input_source = 'ImageFile'
#input_source = 'ImageData'
#input_source = 'EncodedImage'
use_lpd_judgement = False
if use_lpd_judgement:
lpd_judge_cb.judgement_type = "the best"
lpd_judge_cb.min_confidence = 10.0
# [+]Collect the input images.
count = 0
img_files = glob.glob('F:\\Temp2\\*.jpg')
total = len(img_files)
if total == 0:
print("There is no image file.")
quit()
# [-]
# 1. Initialize Evo engine library. Optionally can get DDI object
ddi = PyEvo.DDI()
PyEvo.initialize(None, None, ddi)
# Optionally can examine the DDI.
info = ddi.get()
print(info)
print()
del ddi # Explicitly release the DDI object.
# 2. Create a Snapshot Engine.
sse = PyEvo.SSEngine()
# 3. Initialize the engine.
sse.init('KOR', None)
# [+] 4. If required, set or get engine parameters of interest.
search_rect = sse.get_param_search_rect()
print("<< Search Rectangle >>")
print(f' x : {search_rect.x}')
print(f' y : {search_rect.y}')
print(f' width : {search_rect.width}')
print(f' height: {search_rect.height}')
if use_lpd_judgement:
sse.set_param_lpd_judge_cb(lpd_judge_cb)
# [-]
for img_path in img_files:
print("\n=====================================")
print("[{}]".format(img_path))
# 5. Run the engine with input image.
if input_source == "ImageFile":
lpi = sse.run_with_imgfile(img_path)
elif input_source == "ImageData":
lpi = sse.run_with_imgdata(get_img_data(img_path))
else: # In case of 'EncodedImage'
encimg = get_enc_img(img_path)
lpi = sse.run_with_encimg(encimg)
# 6. Examine the LPI.
if not lpi.is_empty():
print("")
print_lpi(lpi)
# Explicitly release the LPI object.
del lpi
count += 1
# 7. Deinitialize the engine.
sse.deinit()
# 8. Explicitly destroy the engine.
del sse
percent = (count / total) * 100.0;
print("\n\n{} / {} ({}%) passed.".format(count, total, percent))

Example for Triggered Snapshot Engine

import time
import ctypes
import threading
import PyEvo
#=====================================================
#
#
#
#=====================================================
def lpd_judge_cb(imgsz, rects, confidences, num, results):
'''
Arguments
imgsz : Array of 'PyEvo.Rect' type.
There is only one element which describes size of the input image.
rects : Array of 'PyEvo.Rect' type.
Describe bounding boxes of all the detected license plates.
confidences : Array of float type.
Describe confidences of all the detected license plates.
Ranges of the values are between 0 and 100.
num : Single value of int type.
Total number of detected license plates.
results : Array of int type.
Determine whether each detected license plate is correct (0: incorrect, 1: correct).
By default, all the elements are 0s.
'''
_imgsz = imgsz[0] # Only sinlge element is valid.
print("")
# Print size of the input image.
fmtstr = "Image Size : Width({}), Height({})";
print(fmtstr.format(_imgsz.width, _imgsz.height))
# Print count of the detections.
fmtstr = "Detection Count: {}";
print(fmtstr.format(num))
print("")
for i in range(num):
# Print index of the detection.
print(" Index : {}".format(i))
# Print bounding-box of the detection.
# Note the detected bounding-box can be different from the recognized one.
fmtstr = " Bounding Box: x({}), y({}), width({}), height({})";
print(fmtstr.format(rects[i].x, rects[i].y, rects[i].width, rects[i].height))
# Print confidence of the detection.
print(" Confidence : {:.2f}%".format(confidences[i]))
print("--------------------------------------------")
if lpd_judge_cb.judgement_type == "the best":
# [+]
best = -1
maxarea = 0
for i in range(num):
area = rects[i].width * rects[i].height;
if (area > maxarea) and (confidences[i] >= lpd_judge_cb.min_confidence):
maxarea = area
best = i
if best >= 0: results[best] = 1
# [-]
elif lpd_judge_cb.judgement_type == "all":
for i in range(num): results[i] = 1
else:
pass # Ignore all the detected license plates.
return 0
#=====================================================
#
#
#
#=====================================================
def print_lpi(lpi):
result = lpi.gather()
fmtstr = "String : '{}'\n"
fmtstr += "Position: x({}), y({}), width({}), height({})\n"
fmtstr += "LP-Type : {} ({:.2f}%)"
for info in result:
output = fmtstr.format(info['string'],
info['position'].x,
info['position'].y,
info['position'].width,
info['position'].height,
info['lp_type'],
info['lp_conf'])
print(output)
#=====================================================
#
#
#
#=====================================================
def timer_handler():
global tsse
global img_dir
global is_continue
global trigger_timer
(lpi, pic) = tsse.trigger()
if not lpi.is_empty():
print("")
print_lpi(lpi)
# Explicitly release the LPI object.
del lpi
pic.save_in_jpeg('{}\\{}.jpg'.format(img_dir, pic.get_time(1)))
# Explicitly release the Picture object.
del pic
if is_continue:
threading.Timer(1, timer_handler).start()
use_lpd_judgement = False
#url = 'rtsp://192.168.1.100:554/profile3/media.smp'
url = 'F:\\Temp1\\2014-11-24_.mkv'
img_dir = 'F:\\Temp7' # Directory for the images to be saved.
is_continue = True
if use_lpd_judgement:
lpd_judge_cb.judgement_type = "the best"
lpd_judge_cb.min_confidence = 10.0
# If required, create DDI object.
ddi = PyEvo.DDI()
# 1. Initialize Evo engine library.
# If 'EVOENG_DATA_DIR' environment variable is not set,
# the argument 'data_dir' must be set to SDK's data directoy.
PyEvo.initialize(None, None, ddi)
# If required, examine the DDI.
info = ddi.get()
print(info)
print()
del ddi # Explicitly destroy the DDI object.
# 2. Create a Triggered Snapshot Engine.
tsse = PyEvo.TSSEngine()
# 3. Initialize the engine with video source URL or GenICam device.
tsse.init_ipproto('KOR', None, url)
# [+] 4. If required, set or get engine parameters of interest.
search_rect = tsse.get_param_search_rect()
print("<< Search Rectangle >>")
print(f' x : {search_rect.x}')
print(f' y : {search_rect.y}')
print(f' width : {search_rect.width}')
print(f' height: {search_rect.height}')
if use_lpd_judgement:
tsse.set_param_lpd_judge_cb(lpd_judge_cb)
# [-]
# Setup timer to emulate the trigger event.
threading.Timer(1, timer_handler).start()
for num in range(5):
time.sleep(1.0)
is_continue = False
time.sleep(1.5) # To gurantee for the timer handler to terminate safely.
# 5. Deinitialize the engine.
tsse.deinit()
# 6. Destroy the engine.
del tsse

Example for Fully Automatic Video Engine

import time
import ctypes
import PyEvo
#=====================================================
#
#
#
#=====================================================
def lpd_judge_cb(imgsz, rects, confidences, num, results):
'''
Arguments
imgsz : Array of 'PyEvo.Rect' type.
There is only one element which describes size of the input image.
rects : Array of 'PyEvo.Rect' type.
Describe bounding boxes of all the detected license plates.
confidences : Array of float type.
Describe confidences of all the detected license plates.
Ranges of the values are between 0 and 100.
num : Single value of int type.
Total number of detected license plates.
results : Array of int type.
Determine whether each detected license plate is correct (0: incorrect, 1: correct).
By default, all the elements are 0s.
'''
_imgsz = imgsz[0] # Only sinlge element is valid.
print("")
# Print size of the input image.
fmtstr = "Image Size : Width({}), Height({})";
print(fmtstr.format(_imgsz.width, _imgsz.height))
# Print count of the detections.
fmtstr = "Detection Count: {}";
print(fmtstr.format(num))
print("")
for i in range(num):
# Print index of the detection.
print(" Index : {}".format(i))
# Print bounding-box of the detection.
# Note the detected bounding-box can be different from the recognized one.
fmtstr = " Bounding Box: x({}), y({}), width({}), height({})";
print(fmtstr.format(rects[i].x, rects[i].y, rects[i].width, rects[i].height))
# Print confidence of the detection.
print(" Confidence : {:.2f}%".format(confidences[i]))
print("--------------------------------------------")
if lpd_judge_cb.judgement_type == "the best":
# [+]
best = -1
maxarea = 0
for i in range(num):
area = rects[i].width * rects[i].height;
if (area > maxarea) and (confidences[i] >= lpd_judge_cb.min_confidence):
maxarea = area
best = i
if best >= 0: results[best] = 1
# [-]
elif lpd_judge_cb.judgement_type == "all":
for i in range(num): results[i] = 1
else:
pass # Ignore all the detected license plates.
return 0
#=====================================================
#
#
#
#=====================================================
def print_output(lpi, gop):
results = lpi.gather()
# In case of FAVEngine, always return list with single element.
assert (len(results) == 1)
info = results[0]
fmtstr = "String: '{}'\n"
fmtstr += "LP-Type: {} ({:.2f}%)"
print(fmtstr.format(info['string'], info['lp_type'], info['lp_conf']))
for i in range(gop.get_num_pic()):
# Select a specific picture
gop.select_pic(i)
# Get bounding box of each picture.
pos = gop.get_pos_in_pic()
fmtstr = "Position: x({}), y({}), width({}), height({})"
print(fmtstr.format(pos.x, pos.y, pos.width, pos.height))
# Get time of each picture
time_utc = gop.get_pic_time()
time_sec = time_utc // 1000
time_ms = time_utc % 1000
bdt = time.localtime(time_sec) # Borken-Down Time
fmtstr = "Time: {}-{}-{} {}:{}:{}.{}"
print(fmtstr.format(bdt.tm_year,
bdt.tm_mon,
bdt.tm_mday,
bdt.tm_hour,
bdt.tm_min,
bdt.tm_sec,
time_ms))
# Get automobile's heading direction.
heading = gop.get_head_dir()
fmtstr = f'Heading Direction: {heading}'
print(fmtstr)
print("")
global output_dir
if gop.get_num_pic() < 2:
path = f"{output_dir}\\{info['string']}.jpg"
gop.save_pic_in_jpeg(path)
else:
path = f"{output_dir}\\{info['string']}.tiff"
gop.save_all_in_tiff(path)
video_type = "IPProto"
#video_type = "GenICam"
#url = 'rtsp://192.168.1.100:554/profile3/media.smp'
url = 'F:\\Temp1\\2014-11-24_.mkv'
use_lpd_judgement = False
gic = { 'admin': None, 'dev': None } # GenICam related handles
output_dir = 'F:\\Temp4' # Directory for the images to be saved.
if use_lpd_judgement:
lpd_judge_cb.judgement_type = "the best"
lpd_judge_cb.min_confidence = 10.0
# If required, create DDI object.
ddi = PyEvo.DDI()
# 1. Initialize Evo engine library.
# If 'EVOENG_DATA_DIR' environment variable is not set,
# the argument 'data_dir' must be set to SDK's data directoy.
PyEvo.initialize(None, None, ddi)
# If required, examine the DDI.
info = ddi.get()
print(info)
print()
del ddi # Explicitly release the DDI object.
# [+]
if video_type == 'GenICam':
gic['admin'] = PyEvo.GIC.Admin()
gic['admin'].update_dev_list()
num = gic['admin'].get_num_dev()
if num > 0:
for idx in range(num):
gic['admin'].select_dev(idx)
info = gic['admin'].get_dev_info()
print(f'Device Information: {info}')
print('')
gic['admin'].select_dev(0)
gic['dev'] = gic['admin'].open_dev()
num = gic['dev'].get_num_ds()
if num > 0:
print(f'Number of the data streams : {num}')
else:
del gic['dev'] # At first, destroy the GenICam device.
del gic['admin']
quit()
else:
del gic['admin']
quit()
# [-]
# 2. Create a Fully Automatic Video Engine.
fave = PyEvo.FAVEngine()
# 3. Initialize the created engine.
if video_type == 'IPProto':
fave.init_ipproto('KOR', None, url)
else:
fave.init_genicam('KOR', None, gic['dev'], 0)
# [+] 4. If required, set or get engine parameters of interest.
output = fave.get_param_output()
output.headDir = 1
fave.set_param_output(output)
fave.set_param_gop_size(1)
if use_lpd_judgement:
fave.set_param_lpd_judge_cb(lpd_judge_cb)
# [-]
# 5. Get the LPI and realted pictures.
for num in range(3):
(lpi, gop) = fave.pop_lpi()
# When the video stream has been closed.
if lpi.is_empty() and gop.is_empty():
break
print_output(lpi, gop)
# Explicitly release the LPI and GOP.
del lpi, gop
# 6. Deinitialize the engine.
fave.deinit()
# 7. Explicitly destroy the engine.
del fave
# Explicitly destory the GenICam objects.
if video_type == 'GenICam':
del gic['dev'] # At first, destroy the GenICam device.
del gic['admin']

Example for camera calibration

import PyEvo
#=====================================================
#
#
#
#=====================================================
def print_lpi(lpi):
result = lpi.gather()
fmtstr = " String : '{}'\n"
fmtstr += " Position : x({}), y({}), width({}), height({})\n"
fmtstr += " LP-Type : {} ({:.2f}%)\n"
for info in result:
output = fmtstr.format(info['string'],
info['position'].x,
info['position'].y,
info['position'].width,
info['position'].height,
info['lp_type'],
info['lp_conf'])
print(output)
print("")
img_path = 'F:\\Temp3\\Test-180-3.png'
# 1. Initialize Evo engine library.
PyEvo.initialize('latency')
# 2. Create fisheye camera model.
fisheye_model = PyEvo.CC.Fisheye('Test')
max_resol = fisheye_model.get_max_resol()
output_sz = fisheye_model.get_output_size()
print(f'Max resolution: {max_resol.width} x {max_resol.height}')
print(f'Output Size: {output_sz.width} x {output_sz.height}')
print('')
# 3. Create a Snapshot Engine.
sse = PyEvo.SSEngine()
# 4. Initialize the engine.
sse.init('KOR', 'FP32:CPU')
#
# If there are more input images, repeat the stpes 5 ~ 8.
#
# 5. Get rectified image.
pic = fisheye_model.rectify_with_imgfile(img_path)
# 6. Run the engine with the rectified image.
img = pic.get_image()
lpi = sse.run_with_imgdata(img)
# 7. Examine the LPI.
if not lpi.is_empty():
print('')
print_lpi(lpi)
# Must release the LPI context.
sse.free_lpi(lpi)
# If required, save the rectified image.
pic.save_jpeg('F:\\Temp3\\rectified_img.jpg')
# 8. Release the rectified image.
del pic
# 9. Deinitialize the engine.
sse.deinit()
# 10. Destroy the engine.
del sse
# 11. Destory the camera model.
del fisheye_model