在tk中显示摄像头图像

# -*- coding: utf-8 -*-

import cv2
import tkinter as tk
from PIL import Image, ImageTk

root = tk.Tk()

class APP:
    def __init__(self):
        root.title('颜色识别系统')
        #定义主界面,参数前两个表示长和宽,后两个表示启动时显示的左上角坐标
        root.geometry('%dx%d+%d+%d' % (1300, 550, 0, 0)) 


    def GUI(self):
        #定义左边界面
        self.frame_left = tk.Frame(root)
        self.left_page1 = tk.Label(root)
        self.left_page1.pack(side=tk.LEFT)
        self.frame_left.pack()

        #定义右边界面
        self.frame_right = tk.Frame(root)
        self.right_page1 = tk.Label(root)
        self.right_page1.pack(side=tk.RIGHT)
        self.frame_right.pack()

    def camea_cap(self):
        #判断摄像头编号
        camea_nuber = 0
        for i in range(10):
            if cv2.VideoCapture(camea_nuber).isOpened():
                break
            else:
                camea_nuber = camea_nuber + 1
        self.cap = cv2.VideoCapture(cv2.CAP_DSHOW + camea_nuber)

    def video(self):
        ret, img = self.cap.read()
        if ret:
            #显示图像到界面
            img = cv2.flip(img, 1)                         #水平翻转

            img = cv2.cvtColor(img, cv2.COLOR_BGR2RGBA)    #BGR转RGBA格式
            img_Image = Image.fromarray(img)                #array转img,即:多张图层合并成一张图层
            img_PhotoImage = ImageTk.PhotoImage(image=img_Image)#转换成与tk兼容的图像

            self.left_page1.img_tk = img_PhotoImage         #显示图像到指定界面
            self.left_page1.configure(image=img_PhotoImage) #显示图像到指定界面


        root.after(1, self.video)

    def run(self):
        self.camea_cap()
        self.GUI()
        self.video()
        root.mainloop()

def main():
    Start_GUI = APP()
    Start_GUI.run()

if __name__ == '__main__':

	main()

你可能感兴趣的:(python,开发语言)