Exp.2
Exp.2
2. To capture video from Camera, play a video from a file and save a video file.
2. Libraries used:
a) NumPy
b) opencv-python
c) matplotlib
d) scipy
Programs:
1. Read and Display image using OpenCV:
#import the cv2 library
import cv2
#waitkey() waits for a key press to close the window and 0 specifies indefinite loop
dim = img_color.shape
print(dim)
cv2.waitKey(0)
Output :
(148, 204, 3)
Input Image:
Output Image:
• Color: • Grayscale:
• Unchanged:
2. RGB Recognition :
import cv2
image = cv2.imread('opencv.jpg')
cv2.imshow('Original_Image', image)
b,g,r = cv2.split(image)
cv2.imshow('model blue color', b)
cv2.imshow('model green color', g)
cv2.imshow('model red color', r)
cv2.waitKey(0)
cv2.destroyAllWindows()
Output :
import cv2
image = cv2.imread('opencv.jpg')
resized_image = cv2.resize(image,(150,150))
cv2.imshow('resized_image', resized_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
Output :
Input image :
Output image :
4. Video Handling :
Uding WebCam :
import cv2
#open the default camera
cam = cv2.VideoCapture(0)
#get the default frame width and height
frame_width = int(cam.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(cam.get(cv2.CAP_PROP_FRAME_HEIGHT))
#define the codec and create Videowriter object
fourcc = cv2.Videowriter_fourcc('mp4v')
out = cv2.Videowriter('output.mp4', fourcc, 20.0, (frame_width, frame_height))
while True :
ret, frame = cam.read()
#Write the frame to the output file
out.write(frame)
#Display the captured frame
cv2.imshow('Camera', frame)
Output :
Using WebCam :
Result:
The basics of OpenCV Image and Video Handling were learnt using OpenCV-
python in Visual Studio Code.
Post Lab Questions:
1. List out the image and video file formats supported in OpenCV. What are the
formats supported in OpenCV for writing an image into the computer?
OpenCV primarily supports image formats like JPEG (.jpg), PNG, TIFF, BMP, and can
also read formats like GIF, WebP, JPEG 2000, and various PNM (Portable Network Map)
variations.
Commonly supported image formats are:
JPEG (.jpg)
PNG
TIFF
BMP
GIF
WebP
JPEG 2000 (.jp2)
Various PNM formats (like PBM)
2. Differentiate the functions used to read the video inputs from a built-in
camera, an external USB camera and from a video file that is saved in your
local drive
cv2.VideoCapture(0) Reads from built-in or external USB camera
cv2.VideoCapture('filename or filepath') Reads from the specified file in
the given filepath
# read image
img = cv2.imread('cat.jpg')
Output:
Image Dimension: (230, 220, 3)
Image Height: 230
Image Width: 220
Interpolation is a method for constructing new data points based on a set of known
data points. The cv2.resize function uses the interpolation parameter to calculate
pixel values for a new image from the original one. The choice of interpolation
method depends on the situation, as each method has its own merits and
challenges. For example, bicubic interpolation is slower but produces higher-
quality results for upscaling than bilinear interpolation