Learn Python

Learn Data Structure & Algorithm

Learn Numpy

Learn Pandas

Learn Matplotlib

Learn Seaborn

Learn Statistics

Learn Math

Learn MATLAB

Learn Machine learning

Learn Github

OpenCV Introduction

OpenCV Image Read & Write

OpenCV Image Channels

OpenCV Color Conversion

OpenCV Rotation & Crop

OpenCV Text & Shape

OpenCV Video

OpenCV Arithmetics Operation

OpenCV Thresholding

OpenCV Blur & Blending

OpenCV Edge Detection

OpenCV Contours

OpenCV Hough Transformation Lines

OpenCV Moments & Convexhull

OpenCV Morphological Transformation

OpenCV Template Matching

Learn Deep Learning

Learn MySQL

Learn MongoDB

Learn Web scraping

Learn Excel

Learn Power BI

Learn Tableau

Learn Docker

Learn Hadoop

Video related work in opencv

How to play a video?

Input
import numpy as np
import cv2

video_path=r"E:\Notes Programmingg\CSS\css(transaction)\my_video.mp4"

cap=cv2.VideoCapture(video_path)
#videocapter function will capture the video from the path

'''
Let's access the frames of a video. We know that in the video there is a lot of frames and we display those frames one by continuously. So to play we have to get those frames. To do that we will use a while loop.
'''

while cap.isOpened():
   '''
   The loop will be always    true while capturing the image. That's why we used cap.isopened() function
   '''
   ret,frame=cap.read()
'''
   using the read function we will read the frame. After reading we will get two    things. The first one is True or False. True or false means the cap is open or not    and another one is the frame. We have to store these values in two variables (in the    example ret and frame). Now if the value of ret is false then we have to break    the loop. Because ret value false means the cap is not open and if the cap is not open    then no frames will come. That's why no need to run the loop
'''
   if ret:
      vid_image=cv2.resize(frame,(600,400))
      #Here we resize the frames
      cv2.imshow("mid_vid",vid_image)

      if cv2.waitKey(25) & 0xff==ord("q"):
         '''
         waitKey means here we will wait, if the user press the q button then
         the video display
will be off otherwise the video will be shown
         '''

         break
   else:
      break
cap.release()
cv2.destroyAllWindows()
Output

How to change the color format of the video?

Input
import numpy as np
import cv2

video_path=r"E:\Notes Programming\CSS\css(transaction)\my_video.mp4"

cap=cv2.VideoCapture(video_path)
while cap.isOpened():
   '''
   The loop will be always    true while capturing the image. That's why we used cap.isopened() function
  '''
   ret,frame=cap.read()
   gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
   if ret:
      vid_image=cv2.resize(gray,(600,400))
      cv2.imshow("mid_vid",vid_image)

      if cv2.waitKey(25) & 0xff==ord("q"):
         break
   else:
      break
cap.release()
cv2.destroyAllWindows()
Output
How to open system camera?

To access the system camera we have to pass 0 in VideoCapture function. If there is any secondary camera then you have to write 1, -1 or name of the camera.

Input
import numpy as np
import cv2

cap=cv2.VideoCapture(0)

while cap.isOpened():
   ret,frame=cap.read()
   if ret:
      vid_image=cv2.resize(frame,(600,400))
      cv2.imshow("mid_vid",vid_image)

      if cv2.waitKey(25) & 0xff==ord("q"):
         break
   else:
      break
cap.release()
cv2.destroyAllWindows()
Output

How to capture image from system camera?

Input
import matplotlib.pyplot as plt
import cv2
import numpy as np

cap=cv2.VideoCapture(0)

if cap.isOpened():
   ret,frame=cap.read()
   print(ret)
   #Here we will print/display the matrix of image
   print(frame)
   #Here we will display/print the capture image
else:
   ret = False
img1=cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)

'''
Here we capture the image and convert the image into RGB color and store the image into img1 function
'''
plt.imshow(img1)
plt.title("capture image")
plt.xticks([])
plt.yticks([])
plt.show()

cap.release()
Output

How to capture and save video from system camera?

To save the video, the videoWriter() function is used.

Input
import matplotlib.pyplot as plt
import cv2
import numpy as np

cap=cv2.VideoCapture(0)

fourcc=cv2.VideoWriter_fourcc(*"XVID")
'''
fourcc is a manager where we define the video format. The video formats are DIVX, XVID, MJPG, X264, WMV1, WMV2 The most popular and most used format is XVID.
'''
output= cv2.VideoWriter("E:\\output.avi",fourcc,20.0,(640,480))
'''
videoWriter take four parameters first is the file name and location, the second format which we define in fourcc, the fps(frame per second) and resolution(same as resize
function) '''
while cap.isOpened():
   ret,frame=cap.read()
   if ret==True:
      cv2.imshow("frame",frame)
      #This will display the frames which captured by camera.
      output.write(frame)
      if cv2.waitKey(25) & 0xff==ord("q"):
         break
   else:
      break
cap.release()
output.release()
cv2.destroyAllWindows()
Output

How to capture and save video from system camera in gray scale?

Input
import matplotlib.pyplot as plt
import cv2
import numpy as np

cap=cv2.VideoCapture(0)

fourcc=cv2.VideoWriter_fourcc(*"XVID")
output= cv2.VideoWriter("E:\\output.avi",fourcc,20.0,(640,480),0)
'''
videoWriter takes four-parameter first is the file name and location, the second format which we define in fourcc, the fps(frame per second), and resolution(same as resizing function). If we are reading in grayscale then we have to write 0 as a parameter at the end of the VideoWriter() function.
'''
while cap.isOpened():
   ret,frame=cap.read()
   if ret==True:
      gary=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
      cv2.imshow("frame",gary)
      output.write(frame)
      if cv2.waitKey(25) & 0xff==ord("q"):
         break
   else:
      break
cap.release()
output.release()
cv2.destroyAllWindows()
Output

How to do screen record?

At first we have to install pyautogui library.
Command to install:
!pip install pyautogui

Input
import cv2
import pyautogui as p
import numpy as np

#Lets capture the resolution or size of the screen
rs=p.size()

#filename and path in which we want to store recording
fn=input("Please enter the path and file name ")

#defining the fps
fps=60.0

#Let's create a object to save the video
fourcc=cv2.VideoWriter_fourcc(*"XVID")
'''
fourcc is a manager where we define the video format. The video formats are DIVX, XVID, MJPG, X264, WMV1, WMV2 The most popular and most used format is XVID.
'''
output=cv2.VideoWriter(fn,fourcc,fps,rs)
'''
videoWriter take four parameter first is the file name and location,second format which we define in fourcc,the fps(frame per second) and resolution(same like resize function).If we are reading in gray scale then we have to write 0 as a parameter at the end of VideoWriter() function.
'''

#let's give a name to the window
cv2.namedWindow("recording window",cv2.WINDOW_NORMAL)

'''
If you want to resize the window then write:
cv2.resizeWindow("window",(height,width))
'''
while True:
   img=p.screenshot()
   #we will take the screenshot of video and will save it as an array

   f=np.array(img)
   #Here we created the where the screenshot will be saved

   f=cv2.cvtColor(f,cv2.COLOR_BGR2RGB)
   #here we give color to the screenshot image.

   output.write(f)
   #Here we are writing or saving the screenshots to output variable the object

   cv2.imshow("recording window",f)

   if cv2.waitKey(25) & 0xff==ord("q"):
output.release()
cv2.destroyAllWindows()
Output

How to save image from video?

Input
import cv2
import os
import numpy as np

video_path=r"E:\Notes Programming\CSS\css(transaction)\my_video.mp4"

os.makedirs("E:\sub my files")
#create a directory

cap=cv2.VideoCapture(video_path)
#videocapter function will capture the video from the path

'''
Let's access the frames of a video. We know that in the video there is a lot of frames and we display those frames one by continuously. So to play we have to get those frames. To do that we will use a while loop. '''
img_count=1
#We will count the number of images and store it img_count variable
while cap.isOpened():
   ret,frame=cap.read()
   if not ret:
      print("unable to read frame")
      break

      is_img_write=cv2.imwrite(f"E:\sub my files\image{img_count}.jpeg",frame)
      #Here we will save the image if we get it from the frame variable
   if is_img_write:
      #If the is_img_write have any image then print that image
      print(f"E:\sub my files\image{img_count}.jpeg")

   cv2.waitKey(25) & 0xff == ord("q")
   img_count+=1
cap.release()
cv2.destroyAllWindows() Output

How to remove background from camera or video?

Input
import cv2

video_path=r"D:\vv.mp4"

cap=cv2.VideoCapture(video_path)
#videocapter function will capture the video from the pathh

'''
Let's access the frames of a video. We know that in the video there is a lot of frames and we display those frames one by continuously. So to play we have to get those frames. To do that we will use a while loop.
'''
b_r_v=cv2.createBackgroundSubtractorKNN(detectShadows=True)
'''
If you don't want to detect the shadow of the object then don't use detectShadows=True this parameter. Leave the bracket empty
'''

while cap.isOpened():
   ret,frame=cap.read()
   if ret:
      vid_image=cv2.resize(frame,(600,400))
      #Here we resize the frames
      cv2.imshow("mid_vid",vid_image)
      res=b_r_v.apply(frame)
      cv2.imshow("background removed",res)

      if cv2.waitKey(25) & 0xff==ord("q"):
         break    else:
      break

cap.release()
cv2.destroyAllWindows()
Output

CodersAim is created for learning and training a self learner to become a professional from beginner. While using CodersAim, you agree to have read and accepted our terms of use, privacy policy, Contact Us

© Copyright All rights reserved www.CodersAim.com. Developed by CodersAim.