OpenCV

pip install opencv-python

Image

Basic

import cv2

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

cv2.imshow('Original Image', image)
cv2.imwrite('image.jpg', image)

cv2.waitKey(0)
cv2.destroyAllWindows()

Processing

import cv2

# Read the image
image = cv2.imread('image.jpg')

# Convert the image to grayscale
grayscale_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
rgb_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Crop the image
y, h, w, x = 300, 100, 300, 100
cropped_image = image[y:y+h, w:w+x]

# Resize the image by 50%
resized_image = cv2.resize(image, (0, 0), fx=0.5, fy=0.5)

# Rotate the image by 45 degrees
rotated_image = cv2.rotate(image, cv2.ROTATE_90_CLOCKWISE)

# Apply a Canny edge detection filter to the image
edges_image = cv2.Canny(image, 50, 150)

# Wait for a key press to quit
cv2.waitKey(0)
cv2.destroyAllWindows()

Video

Capturing Video from a Camera

import cv2

# Create a VideoCapture object to capture video from the webcam
cap = cv2.VideoCapture(0)

while True:
    # Capture a frame
    ret, frame = cap.read()

    # Check if the frame is read correctly
    if not ret:
        print("Failed to capture frame")
        break

    # Display the frame
    cv2.imshow('Webcam Video', frame)

    # Check if the user wants to quit
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# Release the VideoCapture object
cap.release()
cv2.destroyAllWindows()

Reading Video from a File

import cv2

# Create a VideoCapture object to read video from a file
cap = cv2.VideoCapture('video.mp4')

while True:
    # Capture a frame
    ret, frame = cap.read()

    # Check if the frame is read correctly
    if not ret:
        print("Failed to read frame")
        break

    # Display the frame
    cv2.imshow('Video File', frame)

    # Check if the user wants to quit
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# Release the VideoCapture object
cap.release()
cv2.destroyAllWindows()

Write Video

import cv2

# Create a VideoWriter object to write video to a file
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 480))

# Capture a frame from the webcam
cap = cv2.VideoCapture(0)

while True:
    # Capture a frame
    ret, frame = cap.read()

    # Check if the frame is read correctly
    if not ret:
        print("Failed to capture frame")
        break

    # Write the frame to the video file
    out.write(frame)

    # Display the frame
    cv2.imshow('Webcam Video', frame)

    # Check if the user wants to quit
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# Release the VideoCapture object and VideoWriter object
cap.release()
out.release()
cv2.destroyAllWindows()

Last updated