# Python OpenCV: Getting video from camera

In this tutorial we will learn how to obtain video from a webcam, using Python and OpenCV. We will then display the video on a OpenCV window.

## Introduction

In this tutorial we will learn how to obtain video from a webcam, using Python and OpenCV. We will then display the video on a OpenCV window.

This tutorial was tested on Windows 8.1, with version 4.0.0 of OpenCV. The Python version used was 3.7.2.

The code shown here is based on this tutorial from the OpenCV documentation, which I really encourage you to check.

## The code

We will start our code by importing the cv2 module, which will make available all the functionality we need to capture video from a camera.

```import cv2
```

Then, to obtain video from a camera, we need to create an object of class VideoCapture. As input, the constructor of this class receives the index of the device we want to use. If we just have a single camera connected to the computer, we can simply pass the value 0.

```capture = cv2.VideoCapture(0)
```

After this, we can start reading the video from the camera frame by frame. We do this by calling the read method on or VideoCapture object.

This method takes no arguments and returns a tuple. The first returned value is a Boolean indicating if the frame was read correctly (True) or not (False).

We can use this value for error checking if we want to confirm no problem occurred while reading the frame. Nonetheless, for this introductory tutorial, we will assume everything went well, so we are not going to look into this value.

The second value returned by the read method is a numpy ndarray object representing the captured frame.

```ret, frame = capture.read()
```

Now, to display the captured frame, we simply need to call the imshow function of the cv2 module. This function will open a window and display the frame.

As first input it receives the name of the window, as a string. As second input it receives the image to display. In our case, the image will be the captured frame from the camera.

```cv2.imshow('video', frame)
```

Since we are going to continuously read and display the frames from the camera, we should do the two previous calls inside an infinite loop. Note that when we call the imshow multiple times for the same window, the new image will override the previous one.

In order for us to be able to end the loop, we will use the waitKey function from the cv2 module to check if a given key was pressed.

This function receives as input a delay to wait until the key is pressed, in milliseconds. Naturally, we don’t want the program to be blocked much time waiting for a key because, if nothing gets pressed, we need to fetch the next frame and display it. Thus, we will pass a small value of 1 millisecond.

Note that the waitKey function returns the pressed key as a number. We will assume that we want to finish the program in case the ESC key is pressed. That key corresponds to the number 27.

```if cv2.waitKey(1) == 27:
break
```

The full reading loop can be seen below.

```while(True):

cv2.imshow('video', frame)

if cv2.waitKey(1) == 27:
break
```

After the loop breaks, we no longer need to access the video, so we should release it with a call to the release method on the VideoCapture object.

```capture.release()
```

To finalize, we will call the destroyAllWindows function of the cv2 module, to destroy the window we have created to show the frames of the camera.

```cv2.destroyAllWindows()
```

The final code can be seen below.

```import cv2

capture = cv2.VideoCapture(0)

while(True):

cv2.imshow('video', frame)

if cv2.waitKey(1) == 27:
break

capture.release()
cv2.destroyAllWindows()
```

## Testing the code

To test the code, simply run the previous script on a Python environment of your choice, making sure you have a camera attached o your computed. You should see a result similar to figure 1, which shows the window where the frames of the camera are being displayed.

After you click the ESC key of your keyboard, the window with the video should get closed the the script should finish executing.

1.
{"ft_lang_label":"__label__en","ft_lang_prob":0.8556094,"math_prob":0.8554313,"size":4289,"snap":"2020-45-2020-50","text_gpt3_token_len":960,"char_repetition_ratio":0.12648775,"word_repetition_ratio":0.087671235,"special_character_ratio":0.22499417,"punctuation_ratio":0.12528473,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9597783,"pos_list":[0,1,2],"im_url_duplicate_count":[null,null,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2020-11-25T20:26:15Z\",\"WARC-Record-ID\":\"<urn:uuid:111114c2-586e-4452-8b23-b8915967d378>\",\"Content-Length\":\"83403\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:eaa20dc6-7884-437b-b6c4-0f62397212d8>\",\"WARC-Concurrent-To\":\"<urn:uuid:53bdf663-f895-497a-a96c-15cff714bb85>\",\"WARC-IP-Address\":\"192.0.78.157\",\"WARC-Target-URI\":\"https://techtutorialsx.com/2019/04/13/python-opencv-getting-video-from-camera/\",\"WARC-Payload-Digest\":\"sha1:D3FUEXHWS5M5ZO5OI3NNQXL7QL3YKLQM\",\"WARC-Block-Digest\":\"sha1:NCSN2JNIW32XX2Q7BR2MUCP7CY7ECRZR\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2020/CC-MAIN-2020-50/CC-MAIN-2020-50_segments_1606141184123.9_warc_CC-MAIN-20201125183823-20201125213823-00665.warc.gz\"}"}