Rich's Wordpress

又一个WordPress站点

OpenCV 1: Reading Images and Videos

I decided to start learning how to use the OpenCV library in Python! The OpenCV library is a popular computer vision library for beginners to use, it can be used for jobs like detecting objects and processing videos. By combining this library with Raspberry Pi, I will be able to achieve more applications.

Reading Image:

Through the use of the OpenCV library in Python, it allows me to access the images on my computer via Python.

import cv2 as cv

img = cv.imread('Image/Cat.jpeg') # Takes in a path to an image

cv.imshow('image', img)

cv.waitKey(0)

The name of the OpenCV library is called. cv2, in order to use it, I need first to import this library in the very first line. The way we read images in OpenCV is to use the “cv.imread()” method, this method takes in a path to an image and returns the image as a matrix of pixels. The photo can be assigned to a variable called “img”. After reading this image, we can display this image by using the “cv.imshow()” method which displays this image as a new window. The two parameters that we need to pass into this method are the name of the window and the matrix of pixels to display. In addition, the last line tells the computer to wait for a key to be pressed, in my case, the computer will wait for an infinite amount of time for the key “0” to be pressed before closing the window.

Reading Video:

The OpenCV library not only allows me to open image files but also access videos on my computer.

import cv2 as cv

capture = cv.VideoCapture('Video/Cat.mp4')

while True:
    isTrue, frame = capture.read()

    cv.imshow('Song', frame)

    if cv.waitKey(20) & 0xFF==ord('d'):
        break

capture.release()
cv.destroyAllWindows()

To read a video, we need to use the “cv.VideoCapture()” method. This method takes in an integer like 0, 1 or 2 (if I am using a webcam or a camera connected to my computer) as a parameter or a path to a video file in the computer. Reading a video is different to reading an image, we need to read the video frame by frame using a while loop. The method “capture.read()” reads in the video frame-by-frame and the part “isTrue” returns a boolean to track whether the frame is returned successfully or not. Next, each frame is displayed using the “cv.imshow” method. After that, to stop the video from playing indefinitely, we need the if statement to break out of the while loop if the key “d” is pressed. Finally, the method “cv.destroyAllWindows()” will close all the window as it is now needed anymore.

OpenCV 1: Reading Images and Videos
Scroll to top