Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

ใช้ OpenCV ร่วมกับ Tkinter แสดงกล้องเว็บแคม

รวม OpenCV (Computer Vision) กับ Tkinter GUI ต้องติดตั้ง:

pip install opencv-python
pip install Pillow

หลักการ

  1. OpenCV อ่านเฟรมจากกล้อง cv2.VideoCapture(0)
  2. แปลง BGR → RGB
  3. สร้าง PIL Image → ImageTk.PhotoImage
  4. แสดงใน Label, ใช้ after() วนลูปอัปเดต

ตัวอย่างโค้ด

from tkinter import *
from PIL import Image, ImageTk
import cv2

win = Tk()
win.geometry("700x350")

label = Label(win)
label.grid(row=0, column=0)

cap = cv2.VideoCapture(0)

def show_frames():
    ret, frame = cap.read()
    if ret:
        cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        img = Image.fromarray(cv2image)
        imgtk = ImageTk.PhotoImage(image=img)
        label.imgtk = imgtk
        label.configure(image=imgtk)
    label.after(20, show_frames)

show_frames()
win.mainloop()

ผลลัพธ์

หน้าต่าง Tkinter แสดงภาพจากกล้องเว็บแคมเรียลไทม์

ใช้ OpenCV ร่วมกับ Tkinter แสดงกล้องเว็บแคม