ไลบรารี Python มีความเป็นอิสระและสามารถใช้เพื่อวัตถุประสงค์ที่แตกต่างกันได้ในขณะที่สร้างแอปพลิเคชันเด่นเฉพาะ ในตัวอย่างนี้ เราจะสร้างแอปพลิเคชันโดยใช้ไลบรารี OpenCV และ Tkinter OpenCV คือไลบรารี Python ที่ใช้ในการทำงานร่วมกับ Computer Vision และสิ่งประดิษฐ์ประดิษฐ์อื่นๆ เมื่อใช้โมดูล OpenCV เราต้องแสดงเว็บแคมในหน้าต่าง tkinter
ในการสร้างแอปพลิเคชัน คุณจะต้องติดตั้ง open-cv ในเครื่องของคุณและตรวจสอบให้แน่ใจว่า แพ็คเกจหมอน Python ถูกติดตั้งไว้ล่วงหน้า คุณสามารถติดตั้งแพ็คเกจเหล่านี้ได้โดยพิมพ์คำสั่งต่อไปนี้
pip install open-cv pip install Pillow
เมื่อติดตั้งเสร็จแล้ว เราสามารถเริ่มสร้างโครงสร้างและ GUI ของแอปพลิเคชันได้ ฟังก์ชันพื้นฐานของแอปพลิเคชันของเราคือเปิดกล้องเว็บ (ถ้าเป็นไปได้) โดยใช้ OpenCV ดังนั้น เพื่อแสดงเฟรมที่จับภาพทุกเฟรม เราสามารถใช้แพ็คเกจ Python Pillow (PIL) ซึ่งแปลงเฟรมเป็นอิมเมจ ตอนนี้รูปภาพสามารถใช้ในวิดเจ็ตป้ายกำกับที่แสดงทุกเฟรมที่จับภาพซ้ำในหน้าต่างได้
ตัวอย่าง
# Import required Libraries
from tkinter import *
from PIL import Image, ImageTk
import cv2
# Create an instance of TKinter Window or frame
win = Tk()
# Set the size of the window
win.geometry("700x350")
# Create a Label to capture the Video frames
label =Label(win)
label.grid(row=0, column=0)
cap= cv2.VideoCapture(0)
# Define function to show frame
def show_frames():
# Get the latest frame and convert into Image
cv2image= cv2.cvtColor(cap.read()[1],cv2.COLOR_BGR2RGB)
img = Image.fromarray(cv2image)
# Convert image to PhotoImage
imgtk = ImageTk.PhotoImage(image = img)
label.imgtk = imgtk
label.configure(image=imgtk)
# Repeat after an interval to capture continiously
label.after(20, show_frames)
show_frames()
win.mainloop() ผลลัพธ์
เมื่อใดก็ตามที่เราเรียกใช้โค้ดข้างต้น มันจะเปิดเว็บแคมและผลลัพธ์จะแสดงในหน้าต่าง tkinter
