How to get started with OpenCv in Python

How to get started with OpenCv in Python

Hi! Welcome in this article! Today we’ll see how to get started with OpenCv in python.

Installing the library

To install the OpenCv library type

pip install opencv-contrib-python
pip install caer

The first library is not the basic OpenCv package, it is a package that includes also some contents from the community. So it is a more complete package with more functionalities! I suggest to install it, but if don’t want to get the extras contents type:

pip install opencv-python

Then the library caer has usefull functions that will help.

Let’s see some basic functionalities

Open a Photo

Open an image with the method imread(‘Path of the photo’) and save it in a variable.

Then with the method imshow(‘Name of Window’, img) and wait an infinite time to close it with the method waitKey(0)

import cv2 as cv

img = cv.imread('Photos/dog.jpg')
cv.imshow('NameWindow', img)
Open a Photo with OpenCv

That is how it will look like! How cute is this dog?! Sooo cutee!!!…

Open a Video

Now we will see how to open a video.

First of all we ‘capture’ it and save it in a variable with the method VideoCapture(‘path of the video’).

If you want to capture it from a webcam you don’t have to write the path of the video, but a number 0, 1, 2…and so on depending on the number of your webcam, but we will see that later.

import cv2 as cv

capture = cv.VideoCapture('Videos/dog.mp4')

while True:
    isTrue, frame =  #read frame by frame
    cv.imshow('Video', frame)   #show each frame in a windows 
                                #called Video

    if cv.waitKey(20) & 0xFF==ord('d'):   #if 'd' is pressed stop          
        break                             #the video
capture.release()   #release capture variable
cv.destroyAllWindows()  #destroy the window when the video 

I hope you enjoyed this tutorial on how to getting started with OpenCv in python.

There will be soon more article about OpenCv in python! We will do a full tutorial about it! So enable the notification to get notified when we will publish new articles!

Read the Part 2! How to edit an image with OpenCv in Python!

Davide Busco

Davide Busco is an engineering student at Federico II University of Naples. He uses his passion and studies to create his projects. He loves be a maker and spread his knowledge. Moreover he has gained the second place in a national makers-tournament between Italian's Universities.

Leave a Reply

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