安装
pip install mvtec-halcon==20111
如果halcon不是按照C盘,还需要将如下dll文件放到环境变量里
官方案例1:
"""
************************************************************
console_app.py - Minimal console example for HALCON/Python
************************************************************
Project: HALCON/Python
Description:
Minimal console example that shows how to call HALCON's operators in Python.
************************************************************
(c) 1996-2020 by MVTec Software GmbH
Software by: MVTec Software GmbH, www.mvtec.com
"""
import halcon as ha
if __name__ == '__main__':
img = ha.read_image('pcb')
region = ha.threshold(img, 0, 122)
num_regions = ha.count_obj(ha.connection(region))
print(f'Number of Regions: {num_regions}')
官方案例2:
"""
************************************************************
matching.py - Matching example for HALCON/Python
************************************************************
Project: HALCON/Python
Description:
Program that shows how to locate a chip on a board and measure the pins.
************************************************************
(c) 1996-2020 by MVTec Software GmbH
Software by: MVTec Software GmbH, www.mvtec.com
"""
import math
import os
import sys
import halcon as ha
class SysParamGuard(object):
"""Utility RAII style system parameter guard."""
def __init__(self, parameter_name, active, restore):
self.parameter_name = parameter_name
self.active = active
self.restore = restore
def __enter__(self):
ha.set_system(self.parameter_name, self.active)
def __exit__(self, exc_type, exc_value, traceback):
ha.set_system(self.parameter_name, self.restore)
class RectInfo(object):
"""Rectangle and related information repeatedly used in calculations."""
def __init__(self, base_rect, row_offset, col_offset):
_, self.center_row, self.center_col = ha.area_center_s(base_rect)
self.length = 170.0
self.width = 5.0
self.angle = 0.0
self.row = self.center_row + row_offset
self.col = self.center_col + col_offset
self.base_row = self.row
self.base_col = self.col
def open_framegrabber():
"""Open file based image acquisition framegrabber."""
return ha.open_framegrabber(
name='File',
horizontal_resolution=1,
vertical_resolution=1,
image_width=0,
image_height=0,
start_row=0,
start_column=0,
field='default',
bits_per_channel=-1,
color_space='default',
generic=-1,
external_trigger='default',
camera_type='board/board.seq',
device='default',
port=1,
line_in=-1
)
def open_window(width, height):
"""Open native window for drawing."""
if os.name == 'nt':
# Windows applications wanting to perform GUI tasks, require an
# application level event loop. By default console applications like
# this do not have one, but HALCON can take care of this for us,
# if we enable it by setting this system parameter.
ha.set_system('use_window_thread', 'true')
return ha.open_window(
row=0,
column=0,
width=width,
height=height,
father_window=0,
mode='visible',
machine=''
)
def create_shape_model(template_image):
"""Prepare a shape model for matching."""
return ha.create_shape_model(
template_image,
num_levels=4,
angle_start=0.0,
angle_extent=2 * math.pi,
angle_step=math.pi / 180.0,
optimization='auto',
metric='use_polarity',
contrast=30.0,
min_contrast=10.0
)
def gen_free_rectangle(rect_info):
"""
Compute the coordinates of the measurement rectangles relative to the
center of the model.
"""
return ha.gen_rectangle2(
row=rect_info.row,
column=rect_info.col,
phi=rect_info.angle,
length_1=rect_info.length,
length_2=rect_info.width
)
def gen_measure_rectangle(rect_info, width, height):
"""Prepare extraction of straight edges perpendicular to a rectangle."""
return ha.gen_measure_rectangle2(
row=rect_info.row,
column=rect_info.col,
phi=rect_info.angle,
length_1=rect_info.length,
length_2=rect_info.width,
width=width,
height=height,
interpolation='bilinear'
)
def affine_trans_pixel(hom_mat_2d, rect_info):
"""Compute the parameters of the measurement rectangles."""
return ha.affine_trans_pixel(
hom_mat_2d,
row=rect_info1.base_row,
col=rect_info1.base_col
)
def find_shape_model(acq_img, model):
"""Find the IC in the current image."""
t1 = ha.count_seconds()
row, col, angle, match_score = ha.find_shape_model(
acq_img,
model,
angle_start=0.0,
angle_extent=2 * math.pi,
min_score=0.7,
num_matches=1,
max_overlap=0.5,
sub_pixel='least_squares',
num_levels=4,
greediness=0.7
)
t2 = ha.count_seconds()
match_time = (t2 - t1) * 1000
return row, col, angle, match_score, match_time
def disp_match_res(model_contours, match_res, rect_info1, rect_info2, window):
"""Display shape model match results."""
row, col, angle, match_score, match_time = match_res
hom_mat_2d = ha.vector_angle_to_rigid(
row_1=rect_info1.center_row,
column_1=rect_info1.center_col,
angle_1=0.0,
row_2=row,
column_2=col,
angle_2=angle
)
# Rotate the model for visualization purposes.
rotated_contours = ha.affine_trans_region(
model_contours,
hom_mat_2d,
interpolate='nearest_neighbor'
)
ha.set_color(window, 'green')
ha.disp_obj(rotated_contours, window)
rect_info1.row, rect_info1.col = affine_trans_pixel(hom_mat_2d, rect_info1)
rect_info2.row, rect_info2.col = affine_trans_pixel(hom_mat_2d, rect_info2)
rect_info1.angle = angle
rect_info2.angle = angle
ha.set_color(window, 'blue')
ha.set_draw(window, 'margin')
ha.disp_obj(gen_free_rectangle(rect_info1), window)
ha.disp_obj(gen_free_rectangle(rect_info2), window)
ha.set_draw(window, 'fill')
def measure_pairs(acq_img, measure_rect):
"""
Extract straight edge pairs perpendicular to a rectangle or annulal arc.
"""
return ha.measure_pairs(
acq_img,
measure_rect,
sigma=2,
threshold=90,
transition='positive',
select='all',
)
def disp_line(window, width, row_edge, col_edge):
"""Draws lines in a window."""
ha.disp_line(
window,
[x - width for x in row_edge],
[x - width for x in col_edge],
[x + width for x in row_edge],
[x + width for x in col_edge]
)
def measure(acq_img, rect_info1, rect_info2, img_width, img_height):
"""Do the actual measurements."""
t1 = ha.count_seconds()
measure_rect1 = gen_measure_rectangle(rect_info1, img_width, img_height)
measure_rect2 = gen_measure_rectangle(rect_info2, img_width, img_height)
measure_res1 = measure_pairs(acq_img, measure_rect1)
measure_res2 = measure_pairs(acq_img, measure_rect2)
# Update the lead number label with the measured number of leads.
num_leads = len(measure_res1[6]) + len(measure_res2[6])
t2 = ha.count_seconds()
measure_time = (t2 - t1) * 1000
return measure_res1, measure_res2, num_leads, measure_time
def disp_measure_res(width, measure_res):
"""Display measure results."""
ha.set_color(window, 'red')
disp_line(window, width, measure_res[0], measure_res[1])
disp_line(window, width, measure_res[3], measure_res1[4])
ha.set_draw(window, 'fill')
def print_summary(match_res, num_leads, measure_time):
"""Print match and measure stats."""
_, _, _, match_score, match_time = match_res
print(
f'Match time: {match_time:.2f} [ms], Score: {match_score[0]:.2f}, '
f'Measure time: {measure_time:.2f} [ms], Num Leads: {num_leads}'
)
# Report progress as it comes in, avoids issues with buffered shells.
sys.stdout.flush()
if __name__ == '__main__':
acq_handle = open_framegrabber()
acq_img = ha.grab_image(acq_handle)
img_width, img_height = ha.get_image_size_s(acq_img)
window = open_window(img_width, img_height)
ha.disp_obj(acq_img, window)
# This is the base rectangle we use to base further calculation on.
base_rect = ha.gen_rectangle1(
row_1=188,
column_1=182,
row_2=298,
column_2=412
)
rect_info1 = RectInfo(base_rect, row_offset=-102.0, col_offset=5.0)
rect_info2 = RectInfo(base_rect, row_offset=107.0, col_offset=5.0)
# Create an iconic representation of the model. This region will be
# transformed by the measured position of the model for visualization
# purposes later on.
reduced_image = ha.reduce_domain(acq_img, base_rect)
ha.disp_obj(reduced_image, window)
_, model_contours = ha.inspect_shape_model(
reduced_image,
num_levels=1,
contrast=30.0
)
ha.set_color(window, 'green')
ha.disp_obj(model_contours, window)
# Create the model.
model = create_shape_model(reduced_image)
# Display the model and measurement rectangles.
ha.set_color(window, 'blue')
ha.set_draw(window, 'margin')
ha.disp_obj(gen_free_rectangle(rect_info1), window)
ha.disp_obj(gen_free_rectangle(rect_info2), window)
# Find the model in other images.
for _ in range(100):
with SysParamGuard('flush_graphic', 'false', restore='true') as _:
acq_img = ha.grab_image(acq_handle)
ha.disp_obj(acq_img, window)
match_res = find_shape_model(acq_img, model)
if len(match_res[2]) == 0:
print('No matches found.')
break
disp_match_res(
model_contours,
match_res,
rect_info1,
rect_info2,
window
)
measure_res1, measure_res2, num_leads, measure_time = measure(
acq_img,
rect_info1,
rect_info2,
img_width,
img_height
)
disp_measure_res(rect_info1.width, measure_res1)
disp_measure_res(rect_info1.width, measure_res2)
print_summary(match_res, num_leads, measure_time)
# Force the graphics window update by displaying an offscreen pixel.
ha.disp_line(window, row_1=-1, column_1=-1, row_2=-1, column_2=-1)
ha.wait_seconds(0.1)
python调用halcon
Halcon
threshold (Image, Region, 128, 255)
connection (Region, ConnectedRegions)
select_shape (ConnectedRegions, SelectedRegions1, 'area', 'and', 29000, 99999)
union1 (SelectedRegions1, RegionUnion)
return ()
Python
import halcon as ha
import os
import halcon as ha
import cv2
import numpy as np
from PIL import Image
def open_window(width, height, row=0, col=0):
"""Open native window for drawing."""
if os.name == 'nt':
# Windows applications wanting to perform GUI tasks, require an
# application level event loop. By default console applications like
# this do not have one, but HALCON can take care of this for us,
# if we enable it by setting this system parameter.
ha.set_system('use_window_thread', 'true')
return ha.open_window(
row=row,
column=col,
width=width,
height=height,
father_window=0,
mode='visible',
machine=''
)
Image = ha.read_image('printer_chip/printer_chip_01')
# ha.disp_obj(Image, WindowHandle)
# ha.wait_seconds(2)
img_width, img_height = ha.get_image_size_s(Image)
# window = open_window(img_width, img_height)
# ha.disp_obj(Image, window)
# ha.wait_seconds(2)
program = ha.HDevProgram(r'C:\Users\11716\Desktop\ddd.hdev')
proc = ha.HDevProcedure.load_local(program, 'test2')
proc_call = ha.HDevProcedureCall(proc)
# 设置输入变量Image(形参名)
proc_call.set_input_iconic_param_by_name('Image', Image)
proc_call.execute() # 执行
# 接收输出变量DieGrey(形参名)
result = proc_call.get_output_iconic_param_by_name('RegionUnion')
window = open_window(img_width, img_height)
ha.disp_obj(result, window)
ha.wait_seconds(2)
zoom_in_on_fin
import halcon as ha
import os
import halcon as ha
import cv2
import numpy as np
from PIL import Image
def open_window(width, height, row=0, col=0):
"""Open native window for drawing."""
if os.name == 'nt':
# Windows applications wanting to perform GUI tasks, require an
# application level event loop. By default console applications like
# this do not have one, but HALCON can take care of this for us,
# if we enable it by setting this system parameter.
ha.set_system('use_window_thread', 'true')
return ha.open_window(
row=row,
column=col,
width=width,
height=height,
father_window=0,
mode='visible',
machine=''
)
def zoom_in_on_fin(img, fin_region):
"""Display zoomed in fin region in new window."""
zoom_scale = 2
margin = 5
_, center_row, center_col = ha.area_center_s(fin_region)
row1, col1, row2, col2 = ha.smallest_rectangle1_s(fin_region)
region_height = row2 - row1
region_width = col2 - col1
zoom_window = open_window(
width=(region_width + (2 * margin)) * zoom_scale,
height=(region_height + (2 * margin)) * zoom_scale,
row=100 + (center_row / 2),
col=100 + ((center_col / 2) + 30)
)
ha.set_part(
zoom_window,
row1 - margin,
col1 - margin,
row2 - margin,
col2 - margin
)
ha.disp_obj(img, zoom_window)
ha.wait_seconds(5)
ha.set_color(zoom_window, 'red')
ha.disp_obj(fin_region, zoom_window)
ha.wait_seconds(5)
# Keep the window alive in caller.
Image = ha.read_image('printer_chip/printer_chip_01')
# ha.disp_obj(Image, WindowHandle)
# ha.wait_seconds(2)
img_width, img_height = ha.get_image_size_s(Image)
# window = open_window(img_width, img_height)
# ha.disp_obj(Image, window)
# ha.wait_seconds(2)
program = ha.HDevProgram(r'C:\Users\11716\Desktop\ddd.hdev')
proc = ha.HDevProcedure.load_local(program, 'test2')
proc_call = ha.HDevProcedureCall(proc)
# 设置输入变量Image(形参名)
proc_call.set_input_iconic_param_by_name('Image', Image)
proc_call.execute() # 执行
# 接收输出变量DieGrey(形参名)
result = proc_call.get_output_iconic_param_by_name('RegionUnion')
zoom_window = zoom_in_on_fin(Image, result)
ha.wait_seconds(2)
# window = open_window(img_width, img_height)
# ha.disp_obj(result, window)
# ha.wait_seconds(2)
python显示
threshold (Image, Region, 128, 255)
connection (Region, ConnectedRegions)
select_shape (ConnectedRegions, SelectedRegions1, 'area', 'and', 29000, 99999)
union1 (SelectedRegions1, ImageResult1)
*创建空白图像,将得到的区域贴到上面
get_image_size (Image, Width1, Height1)
gen_image_proto (Image, ImageCleared, 128)
paint_region (ImageResult1, ImageCleared, ImageResult1, 255, 'fill')
return ()
import halcon as ha
import os
import halcon as ha
import cv2
import numpy as np
import halcon as ha
from halcon.numpy_interop import himage_as_numpy_array,himage_from_numpy_array
from PIL import Image
def open_window(width, height, row=0, col=0):
"""Open native window for drawing."""
if os.name == 'nt':
# Windows applications wanting to perform GUI tasks, require an
# application level event loop. By default console applications like
# this do not have one, but HALCON can take care of this for us,
# if we enable it by setting this system parameter.
ha.set_system('use_window_thread', 'true')
return ha.open_window(
row=row,
column=col,
width=width,
height=height,
father_window=0,
mode='visible',
machine=''
)
def zoom_in_on_fin(img, fin_region):
"""Display zoomed in fin region in new window."""
zoom_scale = 2
margin = 5
_, center_row, center_col = ha.area_center_s(fin_region)
row1, col1, row2, col2 = ha.smallest_rectangle1_s(fin_region)
region_height = row2 - row1
region_width = col2 - col1
zoom_window = open_window(
width=(region_width + (2 * margin)) * zoom_scale,
height=(region_height + (2 * margin)) * zoom_scale,
row=100 + (center_row / 2),
col=100 + ((center_col / 2) + 30)
)
ha.set_part(
zoom_window,
row1 - margin,
col1 - margin,
row2 - margin,
col2 - margin
)
ha.disp_obj(img, zoom_window)
ha.wait_seconds(5)
ha.set_color(zoom_window, 'red')
ha.disp_obj(fin_region, zoom_window)
ha.wait_seconds(5)
# Keep the window alive in caller.
image = ha.read_image(r'printer_chip/printer_chip_01')
img_width, img_height = ha.get_image_size_s(image)
# window = open_window(img_width, img_height)
# ha.disp_obj(Image, window)
# ha.wait_seconds(2)
program = ha.HDevProgram(r'C:\Users\11716\Desktop\ddd.hdev')
proc = ha.HDevProcedure.load_local(program, 'test2')
proc_call = ha.HDevProcedureCall(proc)
# 设置输入变量Image(形参名)
proc_call.set_input_iconic_param_by_name('Image', image)
proc_call.execute() # 执行
# 接收输出变量DieGrey(形参名)
result = proc_call.get_output_iconic_param_by_name('ImageResult1')
xxx = himage_as_numpy_array(result)
img= Image.fromarray(cv2.cvtColor(xxx,cv2.COLOR_BGR2RGB))
img.show()
# window = open_window(img_width, img_height)
# ha.disp_obj(result, window)
# ha.wait_seconds(2)
实例
import cv2
import halcon as ha
from halcon.numpy_interop import himage_as_numpy_array,himage_from_numpy_array
from PIL import Image
def halconProcess(cvImg,hdev,algofunc,inputPara,outPara):
image = himage_from_numpy_array(cvImg)
# 确定hdev
program = ha.HDevProgram(hdev)
# 确定函数
proc = ha.HDevProcedure.load_local(program, algofunc)
# 程序调用入口
proc_call = ha.HDevProcedureCall(proc)
# 设置输入变量Image(形参名)
proc_call.set_input_iconic_param_by_name(inputPara, image)
# 执行
proc_call.execute()
# 接收输出变量DieGrey(形参名)
result = proc_call.get_output_iconic_param_by_name(outPara)
xxx = himage_as_numpy_array(result)
# 显示
# img= Image.fromarray(cv2.cvtColor(xxx,cv2.COLOR_BGR2RGB))
# img.show()
return xxx
if __name__ == '__main__':
#
img = cv2.imread(r"C:\Users\Public\Documents\MVTec\HALCON-20.11-Steady\examples\images\printer_chip\printer_chip_01.png")
hdev = r'C:\Users\29939\Desktop\halconAlgo\test1.hdev'
algofunc = 'test'
inputPara = 'Image'
outPara = 'ImageResult1'
res = halconProcess(cvImg=img,hdev= hdev,algofunc=algofunc,inputPara=inputPara,outPara=outPara)
img= Image.fromarray(cv2.cvtColor(res,cv2.COLOR_BGR2RGB))
img.show()