Follow

Reading and writing images and videos using opencv

 Introduction:

OpenCV is a powerful library that allows you to read and write images and videos in various formats. In this tutorial, we will discuss how to read and write images and videos using OpenCV in Python.

Syntax:

To read an image using OpenCV, use the imread() method:

python
img = cv2.imread('image.jpg')

To display an image, use the imshow() method:

python
cv2.imshow('image', img) cv2.waitKey(0) cv2.destroyAllWindows()

To write an image, use the imwrite() method:

python
cv2.imwrite('output.jpg', img)

To read a video using OpenCV, use the VideoCapture() method:

python
cap = cv2.VideoCapture('video.mp4')

To display a video, use the while loop:

python
while(cap.isOpened()): ret, frame = cap.read() if ret == True: cv2.imshow('frame',frame) if cv2.waitKey(25) & 0xFF == ord('q'): break else: break

To write a video, use the VideoWriter() method:

python
out = cv2.VideoWriter('output.mp4', cv2.VideoWriter_fourcc(*'MP4V'), 30, (width,height))

Description:

In the above syntax, the imread() method reads an image and stores it in the img variable. The imshow() method displays the image in a window named "image" using the img variable. The waitKey() method waits for a key event and the destroyAllWindows() method closes all windows.

The imwrite() method writes the img variable to a file named "output.jpg". Similarly, the VideoCapture() method captures the video from a file named "video.mp4" and the VideoWriter() method writes the video to a file named "output.mp4".

Related topics:

Example:

Let's read an image and display it using OpenCV:

python
import cv2 
img = cv2.imread('image.jpg'
cv2.imshow('image', img) 
cv2.waitKey(0
cv2.destroyAllWindows()

Now, let's read a video and display it using OpenCV:

python
import cv2 
cap = cv2.VideoCapture('video.mp4')
 while(cap.isOpened()): 
     ret, frame = cap.read() 
     if ret == True: 
         cv2.imshow('frame',frame) 
         if cv2.waitKey(25) & 0xFF == ord('q'): 
            break 
        else
            break 
cap.release() 
cv2.destroyAllWindows()


No comments:

Post a Comment

Tell us how you like it.