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