Halcon Python接口使用步骤

        个人是先接触Python,后接触Halcon的.

之前虽然python一直没有入门,不过浅尝了opencv-python,pillow,matplotlib等库.

其实是最早听说halcon的,一直觉得很牛逼,胆小没敢亵渎.

后来发现halcon20.11版本增加了python接口,才开始了尝试.

由于halcon联合python相关资料非常的少加上个人基础薄弱,整个过程相对困难.

 接下来说一下使用步骤.

操作系统:win10 64位; halcon:20.11 python:3.8以及以上.我用的3.8.

操作系统和是64位python解释器也需要是64位才行.至于win7还是win10没多大关系.

 如果只使用python那么halcon也可以不装.

首先为python安装halcon支持.

pip install mvtec-halcon==20111

 下来新建一个文件夹,里面新建一个.py文件.将对应版本dll复制进来.

 如果安装了halcon20.11仅仅测试是不需要复制这些DLL的.

Halcon Python接口使用步骤_第1张图片

 下来测试一下能不能用.

import halcon as ha 
Image = ha.read_image('pcb')
Width, Height = ha.get_image_size(Image)
print(Width[0], Height[0])
WindowHandle = ha.open_window(0, 0, Width[0]/2, Height[0]/2,father_window=0,mode='visible',machine='')
gray = ha.rgb1_to_gray(Image)
thres = ha.threshold(gray, 100, 200)
ha.disp_obj(Image, WindowHandle)
ha.wait_seconds(2)
ha.clear_window(WindowHandle)
ha.disp_obj(thres, WindowHandle)
ha.wait_seconds(5)

 可以看到"pcb"显示两秒,二值后5秒结束.

如果没有安装halcon20.11需要将第二行稍做修改,先将图片复制到程序运行目录,在改第二行.

假设图片文件名为"lina.jpg".那么修改第二行:

Image = ha.read_image('lina.jpg')#'lina'也可以,可以不加后缀名.个人习惯加上.

好了看到很多帖子说:VSCode中不加wait_seconds函数显示窗口一闪而过,啥也看不到,在Python自己的IDLE里面显示窗口可以停留,原因暂时未知);;;经过多次实验加无意中发现了这个问题的原因和解决的办法:

为了弄清楚为什么显示窗口一闪而过,首先来官方给了3个例子.

 1.

"""
C:\Users\Public\Documents\MVTec\HALCON-20.11-Progress\examples\python\console_app
console_app.py
"""
"""
************************************************************
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.

"""
C:\Users\Public\Documents\MVTec\HALCON-20.11-Progress\examples\python\matching
matching.py
"""
"""
************************************************************
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)

3.

"""C:\Users\Public\Documents\MVTec\HALCON-20.11-Progress\examples\hdevengine\python\exec_procedures
exec_procedures.py
"""
"""
************************************************************
exec_procedures.py - HDevEngine example for HALCON/Python
************************************************************

Project: HALCON/Python
Description:
Example for executing local and external HDevelop procedures.

Note, HDevEngine is a mutable singleton.

************************************************************

(c) 1996-2020 by MVTec Software GmbH

Software by: MVTec Software GmbH, www.mvtec.com
"""

import os

import halcon as ha


def open_window(width, height, row, col):
    """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 setup_hdev_engine():
    """Setup HDevEngine by setting procedure search paths."""
    example_dir = ha.get_system_s('example_dir')
    hdev_example_dir = os.path.join(example_dir, 'hdevengine')

    engine = ha.HDevEngine()
    engine.set_procedure_path(os.path.join(hdev_example_dir, 'procedures'))

    return hdev_example_dir


def init_acq_handle(program):
    """Execute procedure for image acquisition."""
    proc = ha.HDevProcedure.load_local(program, 'init_acquisition')
    proc_call = ha.HDevProcedureCall(proc)
    proc_call.execute()
    return proc_call.get_output_control_param_by_name('AcqHandle')


def display_fin(window, fin_region, fin_area):
    """Draw fin region and info into window"""
    ha.set_color(window, 'red')
    ha.set_draw(window, 'margin')
    ha.disp_obj(fin_region, window)

    ha.set_color(window, 'white')
    ha.set_tposition(window, 150, 20)
    ha.write_string(window, f'Fin Area: {fin_area[0]}')


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.set_color(zoom_window, 'red')
    ha.disp_obj(fin_region, zoom_window)

    # Keep the window alive in caller.
    return zoom_window


if __name__ == '__main__':
    hdev_example_dir = setup_hdev_engine()

    program = ha.HDevProgram(
        os.path.join(hdev_example_dir, 'hdevelop', 'fin_detection.hdev')
    )

    proc = ha.HDevProcedure.load_local(program, 'detect_fin')
    proc_call = ha.HDevProcedureCall(proc)

    acq_handle = init_acq_handle(program)

    for _ in range(3):
        acq_img = ha.grab_image(acq_handle)
        width, height = ha.get_image_size_s(acq_img)

        window = open_window(width, height, row=100, col=100)
        ha.disp_obj(acq_img, window)

        proc_call.set_input_iconic_param_by_name('Image', acq_img)
        proc_call.execute()
        fin_region = proc_call.get_output_iconic_param_by_name('FinRegion')
        fin_area = proc_call.get_output_control_param_by_name('FinArea')

        display_fin(window, fin_region, fin_area)
        input('Press Enter to continue...')

        zoom_window = zoom_in_on_fin(acq_img, fin_region)
        input('Press Enter to continue...')

官方给的第二个例子注释是这样的. 

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=''
    )

所以得出结论:命令行程序不加wait_seconds函数显示窗口一闪而过是正常的. 

那么为什么VScode一闪而过,而用IDLE和Thonny打开同样的程序则窗口可以保持呢? 个人觉得是IDLE和Thonny在不关闭图形窗口的情况下资源没有完全释放导致的. 所以窗口要保持就得让此程序一直阻塞,

下来偷个懒:直接上一个带界面的程序. 

为了实现滚轮缩放和鼠标拖拽引入了C#>winform>picturebox控件到TKinter中.

实际上基本抄的C#程序. 用C#可能更舒服一些.

至此本次的目的是为了可以明显看到在TKinter中窗口是保持的.

from tkinter import ttk
from tkinter import messagebox
from tkinter import *
import tkinter as tk
import tkinter.messagebox
import os,sys,time,configparser,win32gui,pyautogui
import pygetwindow as gw
import tkinter.filedialog
import platform
system          =  platform.system()
plat_version    =  platform.platform()
plat_tuple      =  platform.architecture()
if system == 'Windows':#判断平台是不是windows10 64位; 还是Windows7_64位;
    print('Windows:>version is: '+plat_version+"\n") #返回的则是当前系统的版本号.
    print(f"""系统版本号:{platform.version()}  
          系统的结构:(64位or32位):{platform.machine()}  
          详情:{ platform.uname()}""")
elif system == 'Linux':
    print('this is linux system:version is: '+plat_version)
    pass
def cmd(s="pause"):
    os.system(s)
def checkmorepro(S1="管理员:  SavePp"):# 命令行"管理员:  "+title是真正的标题名
    ''' 防止程序多开'''
    N=gw.getAllTitles();print(f"{N}\n");
    for x in N:
        if x !="":
            if x==S1:
                sys.exit()
            print(f"{x}");
    print(f"\n");
#checkmorepro();#''' 防止程序多开 虽然这样不对 先这样 能用'''
cmd(f"title SavePp")
from ctypes import *
import clr,sys,System,time
from System import String, Char, Int32,UInt16, Int64, Environment, IntPtr
Hsl = clr.AddReference("HslCommunication");print(Hsl);  print("\n")
import HslCommunication
import HslCommunication.Profinet.Siemens#西门子通讯. 
from HslCommunication.Profinet.Siemens import *
import HslCommunication.LogNet#日志
from HslCommunication.LogNet import *   
logNet = LogNetDateTime("./Logs", GenerateMode.ByEveryDay);#../Logs#上级的Logs文件夹; #./Logs #同级的Logs文件夹;
def WriteLog(X=""):
    logNet.WriteAnyString(f"{time.strftime('%H:%M:%S')}:>  {X}");
    print(f"{time.strftime('%H:%M:%S')}:>  {X}")   
WriteLog("启动程序")
import pygetwindow as gw
import keyboard as kb
from tkinter import Tk,Frame
from webbrowser import open as webopen
import ctypes
user32=ctypes.windll.user32
import halcon as ha     #导入python的halcon20.11支持
import clr;print("include Winform_ALL")
print(f"{clr.AddReference('System')}")
print(f"{clr.AddReference('System.Windows.Forms')}")
print(f"{clr.AddReference('System.Drawing')}")
print(f"{clr.AddReference('System.ComponentModel')}")
print(f"{clr.AddReference('System.Data')}")
print(f"{clr.AddReference('System.Linq')}")
print(f"{clr.AddReference('System.Threading.Tasks')}")
print(f"{clr.AddReference('HalconDotNet')}")
import HalconDotNet
from HalconDotNet  import * #把Halcon 20.11的窗体拿过来 现在没用上.
from System.Windows.Forms import MonthCalendar
from System.Windows.Forms import PictureBox
from System.Drawing import Font
from System import String,Single;print("Loading complete");print("完成111");
#WindowHandle=HObject()
#global WindowHandle
WindowHandle=0#窗口句柄
WindowID=0#窗口句柄
ImageWidth=0#图像宽度 
ImageHeight=0#图像高度
RowDown=0;#//鼠标按下时的行坐标
ColDown=0;#//鼠标按下时的列坐标
ho_image=HalconDotNet.HObject()#图像变量
HHID=HTuple()
# 创建图片框类型
class TkPictureBox(Frame):
    global TkPicID
    global TKlabe2
    global label
    def __init__(self,master,width,height):
        global TkPicID
        Frame.__init__(self,master,width=width,height=height)
        self.ca=PictureBox()
        self.cahwnd=int(str(self.ca.Handle))
        TkPicID=int(str(self.ca.Handle));print(f"lwinformpicbox:>>>{int(str(self.ca.Handle))}");# /
        user32.SetParent(self.cahwnd,self.winfo_id())#找个爸爸
        user32.MoveWindow(self.cahwnd,0,0,width,height,True)#显示位置
        self.__bind_event()
        self.bind('',self.__resize)   
    def OutputID(self):
        return int(str(self.ca.Handle))  
    def __bind_event(self):#winform事件绑定
        self.ca.MouseDown +=self.__MouseDown#鼠标按下 
        self.ca.MouseMove +=self.__MouseMove#鼠标移动 
        self.ca.MouseUp   +=self.__MouseUp  #鼠标抬起
        self.ca.MouseWheel+=self.__MouseWheel#滚轮缩放 
        #self.ca.ActiveControl=self.ca
        #this.ActiveControl = this.panelPic;
    def __resize(self,event):#尺寸跟着父类走
        self.ca.Width=self.winfo_width()
        self.ca.Height=self.winfo_height()  
    def __MouseMove(self,sender,e):#print("鼠标    移动  事件!")
        global ImageHeight
        global ImageWidth
        global TKlabe2
        global label
        pointGray="";
        try:#实测,鼠标按下并且划过窗体之外会产生这个错误
            Row,Column,Button =ha.get_mposition(WindowHandle);
        except:
            print("__MouseMove:ha.get_mposition_error")
            return;
        imgH=ImageHeight[0] #ImageHeight ImageWidth 是list类型,取出[0] 从零开始所以-1;
        imgW=ImageWidth[0]
        print(f"{imgH} {imgW}")
        print(f"X0,Y0灰度值 :{ha.get_grayval(Image,0,0)}");
        xxx="";
        xxx+=str(Column+1)#X
        xxx+=" * "
        xxx+=str(Row+1)#Y
        xxx+=" "
        if int(str(Column))>-1 and int(str(Column))-1 and int(str(Row)) 0:
            Zoom = 1.5;
        else:
            Zoom = 0.5;
        Row,Col,Button =ha.get_mposition(WindowHandle);
        Row0,Column0,Row00,Column00 = ha.get_part(WindowHandle);
        Ht = Row00 - Row0;
        Wt = Column00 - Column0;
        if Ht * Wt < 32000 * 32000 or Zoom == 1.5:
            r1 = (Row0 + ((1 - (1.0 / Zoom)) * (Row - Row0)));
            c1 = (Column0 + ((1 - (1.0 / Zoom)) * (Col - Column0)));
            r2 = r1 + (Ht / Zoom);
            c2 = c1 + (Wt / Zoom);
            ha.set_part(WindowHandle, r1, c1, r2, c2)
            ha.clear_window(WindowHandle)
            ha.disp_obj(Image,WindowHandle)            
            #********************滚轮事件**结束******************  
if __name__=='__main__':
    global TkPicID #用于传递PictureBox句柄.
    global label
    global TKlabe2
    a=Tk()
    a.geometry('1000x800+5+5')
    a.title('pyhalcon')
    a.iconbitmap('3D.ico')            #界面图标
    frame1_width=800;frame1_height=540;
    frame1 = tk.Frame(a,width=frame1_width, height=frame1_height, relief='raised', borderwidth=0)
    frame1.config(bg="#000000");frame1.place(x=150, y=50);frame1ID=frame1.winfo_id()
    TkPictureBox1=TkPictureBox(frame1,796,530)
    TkPictureBox1.place(x=2,y=2)
    print(f".cahwnd:>{TkPictureBox1.cahwnd}")
    WinWidth=frame1_width-2-2;WinHeight =frame1_height-2-2;
    WindowHandle  = ha.open_window(0, 0, WinWidth,WinHeight,father_window= TkPicID,mode='visible',machine='')
    WindowID=WindowHandle;
    Image = ha.read_image('Lena.jpg')
    ImageWidth,ImageHeight=ha.get_image_size(Image)
    Width, Height = ha.get_image_size(Image)
    print(Width[0], Height[0])
    ha.disp_obj(Image,WindowHandle)
    ha.set_part(WindowHandle,0,0,-1,-1)
    #get_mposition 大写变小写 Get变get_ ;Set变 set_ ;get_image_size(Image)长句分段
    def askfile():
        filename = tkinter.filedialog.askopenfilename()
        if filename != '':
             return filename
        else:
             return None    
    def click_button(): #
        global Image
        global WindowHandle
        global ImageHeight
        global ImageWidth
        path=askfile()
        Image = ha.read_image(path)
        ImageWidth,ImageHeight=ha.get_image_size(Image)
        label.config(text=f"{ImageWidth} x {ImageHeight}")
        ha.clear_window(WindowHandle)
        ha.disp_obj(Image,WindowHandle)
        ha.set_part(WindowHandle,0,0,-1,-1)
        #
        #获取图像大小 调整图像框长宽比例 使显示比例   
        #frame1.config(width=ImageWidth[0], height=ImageHeight[0]);#
        click_button1()
    def click_button1(): #
        #window.config(background ="#f150ed")
        global Image
        global WindowHandle
        ha.set_part(WindowHandle,0,0,-1,-1)
        ha.clear_window(WindowHandle)
        ha.disp_obj(Image,WindowHandle)
    button = tk.Button(a,text='选择',bg='#8cb5b3',width=10, height=2,command=click_button)
    button.place(x=20, y=20)
    button1 = tk.Button(a,text='恢复大小',bg='#8cb5b3',width=10, height=2,command=click_button1)
    button1.place(x=20, y=80)
    label = tk.Label(a, text="lable");label.place(x=150, y=0);label.config(text=f"{ImageWidth} x {ImageHeight}")
    TKlabe2 = tk.Label(a, text="lable");TKlabe2.place(x=150, y=20)
    click_button1()
    a.mainloop()

 下面是运行效果.:

python+tkinter联合halcon

halcon的语法和python是如此像.简直一模一样.当然那一小部分区别简直不能影响你对pyhalcon的热爱.

 

 

 

 

你可能感兴趣的:(1024程序员节)