ユーザー制御のカメラ機能を Python GUI クロックに追加する
前のチュートリアルでは、Python と Tkinter を使用してカスタマイズ可能な GUI 時計を構築しました。さらに一歩進めて、ユーザーがオンデマンドで画像をキャプチャして保存できるカメラ機能を追加してみましょう。このプロジェクトでは、Python でのカメラ入力の操作を紹介し、GUI 開発とファイル処理のスキルを強化します。
環境のセットアップ
始める前に、必要なライブラリがインストールされていることを確認してください。カメラの処理には OpenCV を使用します。 pip を使用してインストールします:
pip install opencv-python
次に、pip を使用して Pillow をインストールします。
pip install Pillow
すべての依存関係をインストールしたので、カメラを追加できます。通常のカメラとクリックの背後に隠されたカメラの 2 種類のカメラを作成します。
一緒にいてください。
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 は、「最初に見つけたカメラを使用する」ことを意味します (通常はラップトップの内蔵 Web カメラ)。
- 後で参照できるように、このカメラ セットアップ キャップ (キャプチャの略) と呼びます。
if not cap.isOpened(): print("Error: Could not open camera.") return
この部分は、カメラが適切にオンになっているかどうかをチェックします:
- そうでない場合、cap.isOpened(): 「カメラの電源をオンにできませんでしたか?」と尋ねます
- 失敗した場合は、エラー メッセージが出力されます。
-
return は、問題がある場合に「ここで停止して関数を終了する」ことを意味します。
ret、frame = cap.read()
今、実際の写真を撮っています:
cap.read() はカメラのシャッター ボタンを押すのと似ています。
それによって次の 2 つのことが得られます:
- ret: 「写真は正常に撮影されましたか?」に対するはい/いいえの回答
- フレーム: 実際の写真 (撮影された場合)。
if not ret: print("Error: Could not capture image.") cap.release() return
これにより、写真が正常に撮影されたかどうかがチェックされます:
- ret が「いいえ」の場合 (画像が失敗したことを意味します)、次の処理を行います。
エラーメッセージを出力します。
cap.release() はカメラをオフにします。
return は関数を終了します。
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
初心者向けのファイル操作の説明から始めて、次にコードを詳しく見ていきましょう。
初心者向けのファイル操作:
-
読む:
- これは、本を開いてその内容を見るようなものです。
- プログラミングにおいて、ファイルを読み取るとは、その内容を変更せずにアクセスすることを意味します。
- 例: 画像を開いて表示します。
-
書き込み:
- 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.
-
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.
In summary, this function does the following:
- Opens an image file (read operation).
- Resize the image to fit nicely in our GUI window.
- Converts the image to a format our GUI system (Tkinter) can understand.
- 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 中国語 Web サイトの他の関連記事を参照してください。

ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ホットトピック











LinuxターミナルでPythonバージョンを表示する際の許可の問題の解決策PythonターミナルでPythonバージョンを表示しようとするとき、Pythonを入力してください...

fiddlereveryversings for the-middleの測定値を使用するときに検出されないようにする方法

PythonのPandasライブラリを使用する場合、異なる構造を持つ2つのデータフレーム間で列全体をコピーする方法は一般的な問題です。 2つのデータがあるとします...

UvicornはどのようにしてHTTPリクエストを継続的に聞きますか? Uvicornは、ASGIに基づく軽量のWebサーバーです。そのコア機能の1つは、HTTPリクエストを聞いて続行することです...

10時間以内にコンピューター初心者プログラミングの基本を教える方法は?コンピューター初心者にプログラミングの知識を教えるのに10時間しかない場合、何を教えることを選びますか...

Investing.comの反クラウリング戦略を理解する多くの人々は、Investing.com(https://cn.investing.com/news/latest-news)からのニュースデータをクロールしようとします。
