Python calls the camera to realize the camera function

Table of contents

1 Introduction

2. System dependency

(1) OpenCV-Python library

(2) Tkinter library

(3) Pillow library

(4) Time library

3. System code

4. Effect display

5. Precautions


1 Introduction

        This is an interesting project, which realizes the function of taking pictures by calling the camera of the system through a Python program. There are also
        some articles on my homepage that introduce other interesting projects, you can try it yourself:

The blog that can't finish writing code_CSDN Blog Can't finish writing code Good at Python projects, python operation files, system environment configuration, etc. , flask field. https://blog.csdn.net/spx_0108

2. System dependency

(1) OpenCV-Python library

        OpenCV-Python is a Python-based computer vision library that can be used to process image and video data. OpenCV (Open Source Computer Vision Library) was originally developed by Intel Corporation in 1999. OpenCV supports different platforms like Windows, Linux, Android and Mac OS X, and also supports different programming languages, including C++ and Python.

        OpenCV-Python encapsulates the functions in the OpenCV C++ library and provides an easy-to-use API for Python. The calling method of Python API to OpenCV library is relatively simple and intuitive, which makes OpenCV-Python very suitable for beginners and rapid prototyping.

        OpenCV-Python covers many common algorithms and functions in the field of computer vision, such as image processing and analysis, object detection and tracking, machine learning and deep learning, etc. OpenCV-Python also provides some graphical user interface and multimedia processing modules, which are convenient for users to perform image and video input and output operations.

        Overall, OpenCV-Python is a full-featured computer vision library that makes it easy and intuitive to derive information from or manipulate image and video data.

(2) Tkinter library

        Tkinter is a GUI (Graphical User Interface) library built into Python that provides the components and tools needed to create GUI-based desktop applications. Tkinter is a standard library that comes with Python and can be used without additional installation.

        The Tkinter library contains several commonly used modules, including the Tk core module (Tkinter), several widget modules, and a layout management module. Tkinter widgets are the basic units for building GUI interfaces, such as buttons, labels, text boxes, drop-down menus, combo boxes, and scroll bars.

        Tkinter is simple to use and easy to use. Before using Tkinter, you usually need to understand some basic concepts and terms, such as the main window, widgets, event loop, and callback functions.

        In Python, Tkinter can be used to quickly build a graphical user interface, allowing users to use and operate programs through graphical operations. At the same time, Tkinter also supports cross-platform development and can be used on a variety of operating systems, such as Windows, Linux and Mac OS X. In general, Tkinter is a very convenient and practical GUI library, especially suitable for beginners and rapid development of small applications.

(3) Pillow library

        The Pillow library is a branch of the Python Imaging Library branched from the Python Imaging Library (PIL), which provides basic functions for processing images, such as loading, displaying, editing, saving, etc.

        The Pillow library supports a variety of common image formats and can process various types of image data, including bitmap, vector graphics, and RAW formats. In addition, the Pillow library also provides a series of auxiliary functions such as image conversion, color adjustment, filtering, miscut deformation, cropping and scaling.

        The API of the Pillow library is simple and easy to use, so it is very suitable for beginners and intermediate developers working with images. Developers can quickly add image processing functions through the Pillow library, so that their applications can support more image processing requirements.

        In summary, the Pillow library is one of the most used and popular libraries in Python for working with images and image data. When building applications that need to process images and graphics data, using the Pillow library can quickly complete some complex tasks and elevate the application to a higher level.

(4) Time library

        The time library is the standard library in Python for obtaining and manipulating time. It provides a series of functions that can be used to get the current time, calculate the time difference, format the time string, etc.

The time library contains many methods, some of the important methods are as follows:

  • time(): Returns the timestamp of the current time (seconds since January 1, 1970).

  • gmtime(): Returns the UTC time tuple for the current time.

  • localtime(): Returns a time tuple for the current time using the local time zone.

  • asctime(): Convert a time tuple to a readable string form.

  • strftime(): Format a time tuple to the specified format.

  • sleep(): Make the current thread pause for the specified time.

        The time library can be used to obtain the current time, calculate the running time of the function, and perform various operations such as timestamp conversion. The time library is one of Python's standard libraries and can be used without additional installation, and it is one of the most basic and commonly used libraries for dealing with time. If you need to manipulate time in Python, the time library will become one of your powerful tools after mastering its use.

3. System code

import time
import cv2
import tkinter as tk
from PIL import Image, ImageTk


class CameraApp:
    def __init__(self):
        # 创建界面
        self.window = tk.Tk()  # 创建一个窗口对象
        self.window.title("照相机")  # 设置窗口标题
        self.window.geometry("700x600")  # 设置窗口大小

        # 创建显示拍摄照片的控件
        self.photo_label = tk.Label(self.window, width=700, height=550)  # 创建一个标签控件
        self.photo_label.pack()  # 将标签控件添加到窗口中

        # 创建拍照按钮
        self.take_photo_button = tk.Button(self.window, text="拍照", command=self.take_photo)  # 创建一个按钮控件
        self.take_photo_button.pack()  # 将按钮控件添加到窗口中

        # 打开摄像头
        self.cap = cv2.VideoCapture(0)  # 创建一个 VideoCapture 对象,打开默认摄像头
        _, self.frame = self.cap.read()  # 读取摄像头的一帧数据
        self.frame = cv2.cvtColor(self.frame, cv2.COLOR_BGR2RGB)  # 将 BGR 格式的图片转换为 RGB 格式

        self.image_flipped = True  # 控制是否镜像照片

        # 设置界面保持更新
        self.update_frame()

        self.window.mainloop()  # 进入窗口消息循环,等待用户操作

    def update_frame(self):
        _, self.frame = self.cap.read()  # 读取新的摄像头帧数据

        if self.image_flipped:
            self.frame = cv2.flip(self.frame, 1)  # 如果需要镜像显示照片,则在更新帧时进行翻转操作

        self.frame = cv2.cvtColor(self.frame, cv2.COLOR_BGR2RGB)  # 将 BGR 格式的图片转换为 RGB 格式

        # 将摄像头帧转为 PIL 图片格式
        pil_image = Image.fromarray(self.frame)

        # 将 PIL 图片转为 Tkinter 中可以显示的图片格式
        tk_image = ImageTk.PhotoImage(image=pil_image)

        # 更新显示照片的控件图片
        self.photo_label.configure(image=tk_image)  # 将标签控件的图片属性设置为新的图片
        self.photo_label.image = tk_image  # 将标签控件的 image 属性设置为新的图片

        # 循环更新帧
        self.window.after(10, self.update_frame)  # 在 10 毫秒之后调用 update_frame 函数,实现不断更新摄像头帧的效果

    def take_photo(self):
        # 拍照
        _, frame = self.cap.read()  # 读取摄像头的一帧数据

        if self.image_flipped:
            frame = cv2.flip(frame, 1)  # 如果需要镜像照片,则在拍照时进行翻转操作

        # 获取十三位时间戳
        now_time = Utils().getCurrentDateLong()  # 使用 Utils 类中的方法获取当前时间的 13 位时间戳

        # 保存照片,以时间戳命名
        cv2.imwrite(f"./data/{now_time}.jpg", frame)  # 保存图片到指定路径下,以当前时间戳作为文件名

        # 将照片显示在控件中
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)  # 将 BGR 格式的图片转换为 RGB 格式
        pil_image = Image.fromarray(frame)  # 将摄像头帧转换为 PIL 图片格式
        tk_image = ImageTk.PhotoImage(image=pil_image)  # 将 PIL 图片转为 Tkinter 可以显示的图片格式
        self.photo_label.configure(image=tk_image)  # 将标签控件的图片属性设置为新的图片
        self.photo_label.image = tk_image  # 将标签控件的 image 属性设置为新的图片

        print("照片已保存!")


class Utils():
    # 获取 13 位的时间戳
    def getCurrentDateLong(self):
        current_timestamp = int(round(time.time() * 1000))  # 获取当前时间的时间戳(精确到毫秒)
        return current_timestamp

# 主函数
if __name__ == "__main__":
    app = CameraApp()  # 创建 CameraApp 对象,启动程序

4. Effect display

5. Precautions

        If an error occurs, first check whether the package that needs to be imported is missing. If there is a missing package, you can install it on the terminal:

        pip install package name

        If there are other errors, check whether your computer's camera is available, and check whether the camera is being used by other applications.

Guess you like

Origin blog.csdn.net/spx_0108/article/details/131129100