รวม OpenCV (Computer Vision) กับ Tkinter GUI ต้องติดตั้ง:
pip install opencv-python
pip install Pillow
หลักการ
- OpenCV อ่านเฟรมจากกล้อง
cv2.VideoCapture(0) - แปลง BGR → RGB
- สร้าง PIL Image → ImageTk.PhotoImage
- แสดงใน 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 แสดงภาพจากกล้องเว็บแคมเรียลไทม์
