為我們的 Python GUI 時鐘添加使用者控制的相機功能

王林
發布: 2024-07-17 10:55:03
原創
453 人瀏覽過

在先前的教學中,我們使用 Python 和 Tkinter 建立了一個可自訂的 GUI 時脈。讓我們更進一步,添加一個相機功能,讓用戶可以按需捕捉和保存影像。本專案將向您介紹如何在 Python 中使用相機輸入,增強您在 GUI 開發和檔案處理方面的技能。

設定環境

在開始之前,請確保您已安裝必要的庫。我們將使用 OpenCV 進行相機處理。使用 pip 安裝它:

pip install opencv-python
登入後複製

Adding a User-Controlled Camera Feature To Our Python GUI Clock

接下來,我們將使用 pip 安裝 Pillow。

pip install Pillow
登入後複製

現在我們已經安裝了所有依賴項,我們可以新增相機了。我們將創建兩種相機:普通相機和隱藏在點擊後面的相機。

留在我身邊。

    import cv2
    from PIL import Image, ImageTk
    import os
    from datetime import datetime
登入後複製

建立相機功能

讓我們加入一個函數來處理相機捕捉:

    def capture_image():
        # Initialize the camera
        cap = cv2.VideoCapture(0)

        if not cap.isOpened():
            print("Error: Could not open camera.")
            return

        # Capture a frame
        ret, frame = cap.read()

        if not ret:
            print("Error: Could not capture image.")
            cap.release()
            return

        # Create a directory to store images if it doesn't exist
        if not os.path.exists("captured_images"):
            os.makedirs("captured_images")

        # Generate a unique filename using timestamp
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        filename = f"captured_images/image_{timestamp}.png"

        # Save the image
        cv2.imwrite(filename, frame)
        print(f"Image saved as {filename}")

        # Release the camera
        cap.release()

        # Display the captured image
        display_image(filename)
登入後複製

讓我們以初學者容易理解的方式分解 capture_image() 函數。我們將逐步瀏覽每個部分,解釋發生的情況及其原因。

`def capture_image()`
登入後複製

這一行建立了一個名為 capture_image() 的新函數。將函數視為一組指令,我們可以在任何時候想要拍照時使用。

`cap = cv2.VideoCapture(0)`
登入後複製

在這裡,我們正在設定相機。想像一下您正在開啟數位相機:

  • cv2 是一個工具(庫),可以幫助我們在 Python 中處理相機和圖像。
  • VideoCapture(0) 就像按下相機的電源按鈕。 0 表示「使用您找到的第一個攝影機」(通常是筆記型電腦上的內建網路攝影機)。
  • 我們將這個相機設定帽(capture 的縮寫)稱為“capture”,以便我們稍後可以參考。
    if not cap.isOpened():
        print("Error: Could not open camera.")
        return
登入後複製

這部分檢查相機是否正常開啟:

  • 如果不是 cap.isOpened():詢問「相機是否無法開啟?」
  • 如果失敗,我們會列印一條錯誤訊息。
  • return 表示出現問題時「停在這裡並退出函數」。

    ret,frame = cap.read()

現在我們來拍攝實際照片:

cap.read() 就像按下相機上的快門按鈕。

它給了我們兩件事:

  • ret:對「照片拍攝成功了嗎?」的是/否回答
  • 框架:實際照片(如果是拍攝的)。
    if not ret:
        print("Error: Could not capture image.")
        cap.release()
        return
登入後複製

這會檢查照片是否成功拍攝:

  • 如果ret為「no」(表示圖片失敗),我們:
  • 列印錯誤訊息。

  • cap.release() 關閉相機。

  • 回車退出函數。

    if not os.path.exists("captured_images"):
        os.makedirs("captured_images")
登入後複製

這部分建立一個特殊的資料夾來儲存我們的圖片:

if not os.path.exists("captured_images"):` checks if a folder named "captured_images" already exists.
登入後複製
  • 如果不存在,則 os.makedirs("captured_images") 建立此資料夾。
  • 這就像建立一個新相簿來儲存您的照片。
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    filename = f"captured_images/image_{timestamp}.png"
登入後複製

在這裡,我們為我們的圖片創建一個獨特的名稱:

datetime.now() 取得目前日期和時間。
.strftime("%Y%m%d_%H%M%S") 將這次時間格式化為字串,如「20240628_152059」(年-月-日_時分秒)。

  • 我們用它來建立一個檔案名,例如「captured_images/image_20240628_152059.png」。
  • 這確保每張照片都有一個基於拍攝時間的唯一名稱。
    cv2.imwrite(filename, frame)
    print(f"Image saved as {filename}")
登入後複製

現在我們正在儲存圖片。

v2.imwrite(filename,frame) 使用我們建立的檔案名稱來儲存我們的圖片(框架)。
然後我們列印一條訊息,說明圖像的保存位置。

`cap.release()`
登入後複製

這條線會關閉相機,就像完成後再次按下電源按鈕一樣。

`display_image(filename)`
登入後複製

最後,我們呼叫另一個函數來在螢幕上顯示我們剛剛拍攝的圖片。
總之,函數執行以下操作。

  • 打開相機
  • 檢查相機是否正常運作
  • 拍照
  • 確保拍照成功
  • 如果不存在則建立一個資料夾來儲存圖片
  • 依照目前時間為圖片指定唯一的名稱
  • 將圖片保存在資料夾中
  • 關閉相機

每個步驟都會進行檢查,以確保一切正常工作,如果任何時候出現問題,該功能都會停止並讓我們知道出了什麼問題。

顯示拍攝的影像

新增顯示捕捉影像的功能:

    def display_image(filename):
        # Open the image file
        img = Image.open(filename)

        # Resize the image to fit in the window
        img = img.resize((300, 200), Image.LANCZOS)

        # Convert the image for Tkinter
        photo = ImageTk.PhotoImage(img)

        # Update the image label
        image_label.config(image=photo)
        image_label.image = photo
登入後複製

讓我們從適合初學者的文件操作解釋開始,然後深入研究程式碼。

初學者文件操作:

  1. 閱讀:

    • 這就像打開一本書並查看其內容。
    • 在程式設計中,讀取檔案意味著存取其內容而不更改它。
    • 範例:開啟影像進行檢視。
  2. 寫:

    • This is like writing in a notebook.
    • In programming, writing means adding new content to a file or changing existing content.
    • Example: Saving a new image or modifying an existing one.
  3. Execute:

    • This is like following a set of instructions.
    • In programming, executing usually refers to running a program or script.
    • For images, we don't typically "execute" them, but we can process or display them.

Now, let's focus on the display_image(filename) function:

`def display_image(filename)`
登入後複製

This line defines a function named display_image that takes a filename as input. This filename is the path to the image we want to display.

`img = Image.open(filename)`
登入後複製

Here's where we use the "read" operation:

  • Image.open() is a function from the PIL (Python Imaging Library) that opens an image file.
  • It's like telling the computer, "Please look at this picture for me."
  • The opened image is stored in the variable img.
  • This operation doesn't change the original file; it allows us to work with its contents.

    img = img.resize((300, 200), Image.LANCZOS)

This line resizes the image:

  • img.resize() changes the size of the image.
  • (300, 200) sets the new width to 300 pixels and height to 200 pixels.
  • Image.LANCZOS is a high-quality resizing method that helps maintain image quality.

    photo = ImageTk.PhotoImage(img)

This line converts the image for use with Tkinter (the GUI library we're using):

  • ImageTk.PhotoImage() takes our resized image and converts it into a format that Tkinter can display.
  • This converted image is stored in the photo variable.
    image_label.config(image=photo)
    image_label.image = photo
登入後複製

These lines update the GUI to show the image:

  • image_label is a Tkinter widget (like a container) that can display images.
  • config(image=photo) tells this label to display our processed image.
  • image_label.image = photo is a special line that prevents the image from being deleted by Python's garbage collector.

Adding a User-Controlled Camera Feature To Our Python GUI Clock

In summary, this function does the following:

  1. Opens an image file (read operation).
  2. Resize the image to fit nicely in our GUI window.
  3. Converts the image to a format our GUI system (Tkinter) can understand.
  4. Updates a label in our GUI to display this image.

This process doesn't involve writing to the file or executing it. We're simply reading the image, processing it in memory, and displaying it in our application.

Adding GUI Elements

Update your existing GUI to include a button for image capture and a label to display the image:

# Add this after your existing GUI elements
capture_button = tk.Button(window, text="Capture Image", command=capture_image)
capture_button.pack(anchor='center', pady=5)

image_label = tk.Label(window)
image_label.pack(anchor='center', pady=10)
登入後複製
  • Adjusting the Window Size:

You may need to adjust the window size to accommodate the new elements:

window.geometry("350x400")  # Increase the height
登入後複製
  • Complete Code:

Here's the complete code incorporating the new camera feature:

    import tkinter as tk
    from time import strftime
    import cv2
    from PIL import Image, ImageTk
    import os
    from datetime import datetime

    window = tk.Tk()
    window.title("Python GUI Clock with Camera")
    window.geometry("350x400")

    is_24_hour = True

    def update_time():
        global is_24_hour
        time_format = '%H:%M:%S' if is_24_hour else '%I:%M:%S %p'
        time_string = strftime(time_format)
        date_string = strftime('%B %d, %Y')
        time_label.config(text=time_string)
        date_label.config(text=date_string)
        time_label.after(1000, update_time)

    def change_color():
        colors = ['black', 'red', 'green', 'blue', 'yellow', 'purple', 'orange']
        current_bg = time_label.cget("background")
        next_color = colors[(colors.index(current_bg) + 1) % len(colors)]
        time_label.config(background=next_color)
        date_label.config(background=next_color)

    def toggle_format():
        global is_24_hour
        is_24_hour = not is_24_hour

    def capture_image():
        cap = cv2.VideoCapture(0)

        if not cap.isOpened():
            print("Error: Could not open camera.")
            return

        ret, frame = cap.read()

        if not ret:
            print("Error: Could not capture image.")
            cap.release()
            return

        if not os.path.exists("captured_images"):
            os.makedirs("captured_images")

        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        filename = f"captured_images/image_{timestamp}.png"

        cv2.imwrite(filename, frame)
        print(f"Image saved as {filename}")

        cap.release()

        display_image(filename)

    def display_image(filename):
        img = Image.open(filename)
        img = img.resize((300, 200), Image.LANCZOS)
        photo = ImageTk.PhotoImage(img)
        image_label.config(image=photo)
        image_label.image = photo

    time_label = tk.Label(window, font=('calibri', 40, 'bold'), background='black', foreground='white')
    time_label.pack(anchor='center')

    date_label = tk.Label(window, font=('calibri', 24), background='black', foreground='white')
    date_label.pack(anchor='center')

    color_button = tk.Button(window, text="Change Color", command=change_color)
    color_button.pack(anchor='center', pady=5)

    format_button = tk.Button(window, text="Toggle 12/24 Hour", command=toggle_format)
    format_button.pack(anchor='center', pady=5)

    capture_button = tk.Button(window, text="Capture Image", command=capture_image)
    capture_button.pack(anchor='center', pady=5)

    image_label = tk.Label(window)
    image_label.pack(anchor='center', pady=10)

    update_time()
    window.mainloop()
登入後複製

Conclusion

You've now enhanced your GUI clock with a user-controlled camera feature. This addition demonstrates how to integrate hardware interactions into a Python GUI application, handle file operations, and dynamically update the interface.

Always respect user privacy and obtain the necessary permissions when working with camera features in your applications.

Resource

  • How to Identify a Phishing Email in 2024
  • Build Your First Password Cracker
  • Python for Beginners

以上是為我們的 Python GUI 時鐘添加使用者控制的相機功能的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!