# 导入库
import PIL
from PIL import Image,ImageTk
import cv2
from tkinter import *
# 设定宽度、高度
width, height = 800, 540
cap = cv2.VideoCapture(0)
# 设置宽度,高度
cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
root = Tk()
root.bind('<Escape>', lambda e: root.quit())
def motion(event):
pos = ("(%s x %s)" % (event.x, event.y))
possition_lb.configure(text=pos)
def show_frame():
# 从摄像头获取图片
_, frame = cap.read()
frame = cv2.flip(frame, 1)
# 将图片类型从 BGR 转换为 RGB 或 RGBA
cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# 转换为 PIL图片
img = PIL.Image.fromarray(cv2image)
imgtk = ImageTk.PhotoImage(image=img)
img_lb.imgtk = imgtk
# 配置要显示的图片
img_lb.configure(image=imgtk)
# 10 毫秒后调用 show_frame()
img_lb.after(10, show_frame)
# 设定标签以显示视频
img_lb = Label(root,width=800,height=560)
# 捕捉鼠标
img_lb.bind('<Motion>',motion)
img_lb.pack()
text_lb = Label(root,width=15,height=2, text= "Mouse position :")
text_lb.place(x=2, y=575)
# 设定标签以显示位置
possition_lb = Label(root,width=20,height=2)
possition_lb.place(x=100, y=575)
show_frame()
root.geometry("800x600")
root.mainloop()