Display and shoot webcam video with Python Kivy [GUI]

Introduction

Kivy is a library that allows you to develop GUI applications in Python. It is compatible with multiple platforms and can be used for commercial purposes. This time, I will use Kivy to develop a "GUI application that displays and shoots webcam images"! We are also implementing Kivy to easily convert images into buttons!

** * Detailed usage such as Kivy is omitted ** スクリーンショット 2020-07-09 2.56.07.png

environment

pip install

OpenCV


$ pip install opencv-python

Kivy


$ pip install cython pygame pillow
$ pip install Kivy

Practice

Kivy screen creation (Hello World!)

main.py


from kivy.app import App

class MainScreen(Widget):
    pass

class MyCameraApp(App):
    def build(self):
        return MainScreen()

if __name__ == '__main__':
    MyCameraApp().run()

mycamera.kv


<MainScreen>:
    Label:
        text: 'Hello World!'
        center: root.width * 0.5 , root.height * 0.5

I used the Label class to display Hello World !. In Kivy, it is possible to set elements in an HTML-like atmosphere by using a kv file. This time, if Hello World! Is displayed in the middle of the black screen, it is successful.

In the future, we will create a CameraPreview class that displays the acquired image and an ImageButton class for the shooting button, and install them as a kv file in the same way as Label.

Display webcam video

Use OpenCV to get the webcam image as a frame.

Program and description

main.Added to py


from kivy.uix.image import Image
from kivy.graphics.texture import Texture
from kivy.clock import Clock
import cv2

class CameraPreview(Image):
    def __init__(self, **kwargs):
        super(CameraPreview, self).__init__(**kwargs)
        #Connect to 0th camera
        self.capture = cv2.VideoCapture(0)
        #Set drawing interval
        Clock.schedule_interval(self.update, 1.0 / 30)

    #Drawing method to execute at intervals
    def update(self, dt):
        #Load frame
        ret, self.frame = self.capture.read()
        #Convert to Kivy Texture
        buf = cv2.flip(self.frame, 0).tostring()
        texture = Texture.create(size=(self.frame.shape[1], self.frame.shape[0]), colorfmt='bgr') 
        texture.blit_buffer(buf, colorfmt='bgr', bufferfmt='ubyte')
        #Change the texture of the instance
        self.texture = texture

I created a subclass called CameraPreview that inherits from the Image class. This class acquires and updates the webcam image acquired using the opencv-python function. Convert the retrieved frame to Texture format so that it can be displayed in Kivy's Image class.

Next, edit the kv file and reflect it on the screen.

mycamera.kv


<MainScreen>:
    CameraPreview:
        id: camera_preview
        size: root.size

【Caution】 On macOS, if you run the program in a terminal in a third-party editor such as VScode and try to get the webcam image using opencv-python like this program, an error will occur!

Implementation of shooting button

You can use normal buttons, but it's not interesting, so prepare an image like a shooting icon and create a program that allows you to shoot when you click on it. The image has picked up free material appropriately!

Program and description

main.Added to py


from kivy.uix.behaviors import ButtonBehavior
from kivy.properties import ObjectProperty

#Shoot button
class ImageButton(ButtonBehavior, Image):
    preview = ObjectProperty(None)

    #Execute when the button is pressed
    def on_press(self):
        cv2.namedWindow("CV2 Image")
        cv2.imshow("CV2 Image", self.preview.frame)
        cv2.waitKey(0)
        cv2.destroyAllWindows()

In this way, by inheriting not only the Image class but also the ButtonBehavior class, it becomes possible to handle on_press () that is executed when the button is pressed. Override on_press () and rewrite it to the process you want to do.

【important】 Set the ObjectProperty so that it can be referenced in the CameraPreview class. What do you refer to in the variable (preview here) for which ObjectProperty is set? To specify, set in the kv file as follows.

mycamera.kv


<MainScreen>:
    CameraPreview:
        id: camera_preview
        size: root.size
        
    ImageButton:
        preview: camera_preview
        source: 'icons/capture.png'
        size: 100, 100
        center: root.width * 0.5, root.height * 0.2

Declare the variable for which ObjectProperty is set in the Python file in the same way in the kv file, and set the value to the id of the one you want to refer to. (preview: camera_preview part) This allows Kivy to reference values between classes.

Completed program

The program is complete! Let's have Koala, who also appeared at the beginning of the page, appear again. This time, when you click the shooting button, the image is displayed by imshow () of OpenCV, but of course it is possible to rewrite it to the process of saving. スクリーンショット 2020-07-09 2.56.07.png

Supplement

If you get the message You might be loading two sets of Qt binaries into the same process. When you press the shoot button, this should help.

$ pip install opencv-python-headless

Reference site

Recommended Posts

Display and shoot webcam video with Python Kivy [GUI]
GUI programming with kivy ~ Part 3 Video and seek bar ~
[GUI with Python] PyQt5-Drag and drop-
Calculate and display standard weight with python
Happy GUI construction with electron and python
Interactively display algebraic curves with Python and Jupyter
[Python] Webcam frame size and FPS settings with OpenCV
Display USB camera video with Python OpenCV with Raspberry Pi
Programming with Python and Tkinter
Encryption and decryption with Python
Python and hardware-Using RS232C with Python-
YouTube video management with Python 3
[GUI with Python] PyQt5-Layout management-
python with pyenv and venv
[GUI with Python] PyQt5 -Preparation-
Works with Python and R
[GUI with Python] PyQt5 -Paint-
[Python] Read the csv file and display the figure with matplotlib
Convert video to black and white with ffmpeg + python + opencv
I tried to make GUI tic-tac-toe with Python and Tkinter
Communicate with FX-5204PS with Python and PyUSB
Shining life with Python and OpenCV
Install Python 2.7.9 and Python 3.4.x with pip.
Neural network with OpenCV 3 and Python 3
AM modulation and demodulation with python
[Python] font family and font with matplotlib
Scraping with Node, Ruby and Python
[GUI with Python] PyQt5 -Widget II-
Let's make a GUI with python.
Connect a commercially available webcam to a PC with ubuntu 16.04 installed via USB and capture video with python
Scraping with Python and Beautiful Soup
Linking Python and Arduino to display IME On / Off with LED
[GUI with Python] PyQt5-The first step-
Real-time display of video acquired from webcam on Jupyter notebook (Python3)
JSON encoding and decoding with python
Hadoop introduction and MapReduce with Python
Reading and writing NetCDF with Python
I played with PyQt5 and Python3
Reading and writing CSV with Python
Multiple integrals with Python and Sympy
[GUI with Python] PyQt5 -Custom Widget-
[GUI in Python] PyQt5-Menu and Toolbar-
Coexistence of Python2 and 3 with CircleCI (1.0)
Easy modeling with Blender and Python
Sugoroku game and addition game with python
FM modulation and demodulation with Python
Put OpenCV in OS X with Homebrew and input / output video with python
Create a Python3 environment with pyenv on Mac and display a NetworkX graph
Communicate between Elixir and Python with gRPC
[Python] Calendar-style heat map (with holiday display)
Data pipeline construction with Python and Luigi
Monitor Mojo outages with Python and Skype
GUI programming with kivy ~ Part 4 Various buttons ~
FM modulation and demodulation with Python Part 3
[Automation] Manipulate mouse and keyboard with Python
Passwordless authentication with RDS and IAM (Python)
Save video frame by frame with Python OpenCV
Python installation and package management with pip
Using Python and MeCab with Azure Databricks
POST variously with Python and receive with Flask
Execute Google Translate and DeepL Translate with GUI