Here we will learn how to open/load images/videos in OpenCV and display it. There are a few functions in OpenCV to read and display the objects i.e. cv2.imread(), cv2.imshow(). We are using cv2 here.
Read an image using OpenCV
I am using PyCharm for OpenCV which is one the best IDE(Integrated Development Environment) for Python coding.
After creating a project folder, put working directory ‘Resources’ in it.
Sometimes Python interpreter is not set, we must set it in PyCharm by going to
settings >> Project: project_name >> Python Interpreter
then select the proper one and press apply on lower right side of setting window.
A function cv2.imread() is used to read an image in OpenCV. Image must be available in working directory otherwise a full path of image must be given. Here in this case, I have resources folder as a working directory containing an image of light bulb and a video as well. The path of photo will be as follows:
Let us see the code to read an image:
import cv2 img = cv.imread('Resources/light-bulb.jpg') # img is just a variable here cv.imshow('Light Bulb', img) # here 'Light Bulb' is title of loaded image cv.waitkey(0)
Waitkey is important here to make out opened image stayed until we will close it manually by clicking on cross(X) button of its window. If we don’t use waitkey then image will be automatically close in a few milli seconds and can not be seen opened.
Now run the above code, light-bulb.jpg will be displayed.
Load a Video in OpenCV
The follwing is the code for loading or opening video in OpenCV. vidCapture is a variable takes a video from Resource folder. The path is as:
As video contains frames so we are using while loop to get the frames one by one and passing the frames to cv.imshow() function. Similarly waitKey is adjusted at 30 milli second, you can adjust it by your own with other values. On pressing ‘d’ while loop will be broken. Then video will be released and stayed there until all the frames will be passed or you close it manually by clicking cross sign of its window.
vidCapture = cv.VideoCapture('Resources/video.mp4') while True: isTrue, frame = vidCapture.read() cv.imshow('Video',frame) if cv.waitKey(30) & 0xFF==ord('d'): break vidCapture.release() cv.destryAllWindows()
Watch video tutorial to open/load images/videos in OpenCV
Hence you have learned how to open/load images/videos in OpenCV. This series of videos and blogs will cover OpenCV techniques and we will develop our AI apps soon. You can also get a valuable knowledge about machine learning and deep learning through our blogs and videos as we are making learning very simple.