Tutorial: Take pictures from webcam using Python with opencv and PySimpleGUI

In this tutorial we will teach you how to program a camera that allows you to observe and take pictures from your webcam. You will also learn to use opencv for artificial vision processes and also to build simple graphical interfaces with PySimpleGUI

At the end of the tutorial you could download the source code of the program. Let's go ahead:

We start by importing the necessary libraries: 

datetime is included from the Python installation. If you don't have Opencv installed you can do it with the command pip install opencv-python.

To use PySimpleGUI you can also install it with PIP, but it will not be necessary since in the code files I am including a .py file that contains the entire PySimpleGUI library.

Now, we must get access to our webcam, we will do it using Opencv, where the VideoCapture method receives the id of the target camera as a parameter, in this case the webcam.

Once the connection to the webcam is ready, we can define a simple design. We added an image type element which will show the webcam video and a couple of buttons to take a picture and exit the program.

The image_elem variable will allow us to update its content as we get video from the webcam.

To start getting video from the camera we will do it through a while loop, which will be repeated while the camera is open.

As the while loop progresses, we will read the changes that occur in the graphical interface. If the user clicks the "Exit" button, we will exit the while loop and end the execution of the program..

If you click on the "Take Photo" button, a pop-up window will be executed that will request a destination folder to store the photo..

Using the imwrite method we can store the captured image in the chosen path, with the name of the current date.

If no click occurs, we will update the graphic interface with the video from the webcam, for this we must convert the video frame to a bytes type, in this way it will be compatible with the interface.

Followed by this, we will update the image_elem element with the frame converted to bytes.

And finally we call the Main method to execute the program. You can also do it from the console with the command python camera.py

The final program must show the webcam video and allow us to take pictures

If you want to download the source code and support us to bring you more tutorials use the following button

2 thoughts on “Tutorial: Take pictures from webcam using Python with opencv and PySimpleGUI”

  1. Is there a way to take photos when an object is detected? Without pressing a button, that it was automatically when detected.

  2. Very good just one question if I have a form like I draw a box next to the form to take that photo? THANK YOU

Leave a Reply

Your email address will not be published. Required fields are marked *

3 + three =