个人是先接触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的.

下来测试一下能不能用.

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 sysimport halcon as haclass SysParamGuard(object):"""Utility RAII style system parameter guard."""def __init__(self, parameter_name, active, restore):self.parameter_name = parameter_nameself.active = activeself.restore = restoredef __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.0self.width = 5.0self.angle = 0.0self.row = self.center_row + row_offsetself.col = self.center_col + col_offsetself.base_row = self.rowself.base_col = self.coldef 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 thecenter 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) * 1000return row, col, angle, match_score, match_timedef 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_reshom_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 = anglerect_info2.angle = angleha.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) * 1000return measure_res1, measure_res2, num_leads, measure_timedef 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_resprint(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.')breakdisp_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 GmbHSoftware by: MVTec Software GmbH, www.mvtec.com
"""import osimport halcon as hadef 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_dirdef 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 = 2margin = 5_, center_row, center_col = ha.area_center_s(fin_region)row1, col1, row2, col2 = ha.smallest_rectangle1_s(fin_region)region_height = row2 - row1region_width = col2 - col1zoom_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_windowif __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 TkPicIDglobal TKlabe2global labeldef __init__(self,master,width,height):global TkPicIDFrame.__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('<Configure>',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 ImageHeightglobal ImageWidthglobal TKlabe2global labelpointGray="";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)#Xxxx+=" * "xxx+=str(Row+1)#Yxxx+=" "if int(str(Column))>-1 and int(str(Column))<imgW:print("lll")if int(str(Row))>-1 and int(str(Row))<imgH:print("222")xxx +=str(ha.get_grayval(Image,Row,Column))TKlabe2.config(text=f"{(xxx)}")return;TKlabe2.config(text=f"------") def __MouseDown(self,sender,e):#        print("鼠标按下事件!")global RowDownglobal ColDown try:Row,Column,Button =ha.get_mposition(WindowHandle);#取位置except:print("__MouseDown:ha.get_mposition_error")Row=0;Column=0;return;RowDown = Row;    #//鼠标按下时的行坐标ColDown = Column; #//鼠标按下时的列坐标def __MouseUp(self,sender,e):#        print("鼠标  抬起  事件!")try:Row,Column,Button =ha.get_mposition(WindowHandle);except:print("__MouseUp:ha.get_mposition_error")return;RowMove = Row - RowDown;   #//鼠标弹起时的行坐标减去按下时的行坐标,得到行坐标的移动值ColMove = Column - ColDown;#//鼠标弹起时的列坐标减去按下时的列坐标,得到列坐标的移动值row1,col1,row2,col2=ha.get_part(WindowHandle)ha.set_part(WindowHandle, row1 - RowMove, col1 - ColMove, row2 - RowMove, col2 - ColMove)ha.clear_window(WindowHandle)if ImageHeight != None:ha.disp_obj(Image,WindowHandle)else:print("请加载一张图片")def __MouseWheel(self,sender,e):#"滚轮  事件!"Zoom=0;Row=0;Col=0;Button=0;Row0=0;Column0=0;Row00=0;Column00=0;Ht=0;Wt=0;r1=0;c1=0;r2=0;c2=0;if e.Delta > 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 labelglobal TKlabe2a=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 filenameelse:return None    def click_button(): #global Imageglobal WindowHandleglobal ImageHeightglobal ImageWidthpath=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 Imageglobal WindowHandleha.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的热爱.

Halcon Python接口使用步骤相关推荐

  1. Halcon python接口

    1.Halcon HALCON是德国MVtec公司开发的一套完善的标准的机器视觉算法包,拥有应用广泛的机器视觉集成开发环境.它节约了产品成本,缩短了软件开发周期--HALCON灵活的架构便于机器视觉, ...

  2. 安装mysqldb python接口时找不到mysql_config

    我正在尝试使Python脚本在通过ssh连接到的Linux服务器上运行. 该脚本使用mysqldb. 我有我需要的所有其他组件,但是当我尝试通过setuptools安装mySQLdb时,如下所示: p ...

  3. python网络爬虫的基本步骤-黑客基础 编写Python爬虫入门步骤

    原标题:黑客基础 编写Python爬虫入门步骤 信息时代,数据就是宝藏.数据的背后隐含着无穷的宝藏,这些宝藏也许就是信息量所带来的商业价值,而大数据本身也将成为桌面上的筹码. 黑客花无涯 带你走进黑客 ...

  4. python自动化测试视频百度云-Python接口自动化测试 PDF 超清版

    给大家带来的一篇关于Python自动化相关的电子书资源,介绍了关于Python.接口自动化.测试方面的内容,本书是由电子工业出版社出版,格式为PDF,资源大小61.2 MB,王浩然编写,目前豆瓣.亚马 ...

  5. 哪些深度相机有python接口_python 从深度相机realsense生成pcl点云

    简单说下步骤: 一.通过realsense取得深度信息和彩色信息 二.获取坐标和色彩信息 三.通过pcl可视化点云 一.通过realsense取得深度信息和彩色信息 ubuntu下intel real ...

  6. opencv和python的区别_所有这些OpenCV Python接口之间有何不同?

    拉风的咖菲猫 OpenCV正式发布了两种类型的Python接口,cv和cv2.简历:我开始工作cv.这样,所有OpenCV数据类型都将保留下来.例如,加载时,图像的格式cvMat与C ++中的相同.对 ...

  7. ubuntu16.04 安装caffe以及python接口

    http://blog.csdn.net/qq_25073253/article/details/72571714 http://blog.csdn.net/greed7480/article/det ...

  8. python接口自动化测试框架实战从设计到开发_Python接口自动化测试框架实战 从设计到开发...

    第1章 课程介绍(不要错过) 本章主要讲解课程的详细安排.课程学习要求.课程面向用户等,让大家很直观的对课程有整体认知! 第2章 接口测试工具Fiddler的运用 本章重点讲解如何抓app\web的h ...

  9. python接口自动化(十)--post请求四种传送正文方式(详解)

    简介 post请求我在python接口自动化(八)–发送post请求的接口(详解)已经讲过一部分了,主要是发送一些较长的数据,还有就是数据比较安全等.我们要知道post请求四种传送正文方式首先需要先了 ...

最新文章

  1. mysql 8.0 docker_Docker安装MySQL8.0的实现方法
  2. VirtualBox的四种网络连接方式
  3. linux删除文件夹命令6,linux 结合find命令进行文件的删除
  4. Redis的Hash操作
  5. 【转】窗口之间的主从关系与Z-Order
  6. 如何使用Java 8流快速替换列表中的元素
  7. PyTorch学习笔记(六):PyTorch进阶训练技巧
  8. android studio单个工程文件的代理设置
  9. 【转载】使用Lucene.NET实现数据检索功能
  10. 重庆大学数模美赛预选——城市救护车模型
  11. [转载]AdapterView.OnItemClickListener
  12. Vegas Pro给视频加马赛克方法
  13. littleVGL开发(8):消息弹窗控件(lv_mbox)
  14. 【探究服务】——服务的更多技巧
  15. 数据中台与业务中台是什么关系?_光点科技
  16. 改进平滑滚动,修改音量调节级数实现音量微调【编译自XDA 适用于大部分设备】
  17. 记一次Maximo移动端app报错的原因
  18. 算法-查找(红黑树)
  19. OMAP开发板的启动过程
  20. 蛇形走线用于什么方面,一文告诉你

热门文章

  1. PowerDesigner中生成外键FK技巧,powerdesigner导出脚本语言没有外键的处理方法
  2. 新手使用charles时碰到的坑(保姆级教程)
  3. android tv二级菜单,android TV开发:弹出菜单实现
  4. cnpm : 无法加载文件 C:\Users\Cici\AppData\Roaming\npm\cnpm.ps1,因为在此系统上禁止运行脚本
  5. 微软Xbox360 E与微软Xbox360 slim Kinect套装(1TB)哪个好
  6. 团建游戏 人多力量大
  7. linux的unbond服务无法启动,用unbound搭建简单的DNS服务器
  8. 小米平板6什么时候上市?2023年参数配置发布时间最新消息一览
  9. 现实的残酷,离别的痛苦
  10. ZYNQ硬件调试-------day2