2 min read

Python OpenCV Module (cv2)

OpenCV (Open Source Computer Vision Library) is an open-source computer vision and machine learning software library. In Python, it is accessed via the cv2 module.

Installation

pip install opencv-python

Importing the Module

import cv2

Basic Image Operations

Reading and Displaying Images

import cv2

# Read an image
# 1 = Color, 0 = Grayscale, -1 = Unchanged
img = cv2.imread('image.jpg', 1)

if img is None:
    print("Could not read image")
else:
    # Display the image in a window
    cv2.imshow('Image Window', img)

    # Wait indefinitely for a key press
    cv2.waitKey(0)

    # Destroy all windows
    cv2.destroyAllWindows()

Writing Images

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

Image Processing

Converting to Grayscale

gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

Resizing

# Resize to specific dimensions (width, height)
resized = cv2.resize(img, (300, 200))

# Resize by scale factor
scaled = cv2.resize(img, None, fx=0.5, fy=0.5)

Drawing

# Draw a line (img, start, end, color(BGR), thickness)
cv2.line(img, (0, 0), (100, 100), (255, 0, 0), 5)

# Draw a rectangle (img, top-left, bottom-right, color, thickness)
cv2.rectangle(img, (50, 50), (150, 150), (0, 255, 0), 3)

# Draw a circle (img, center, radius, color, thickness)
# Thickness -1 fills the shape
cv2.circle(img, (200, 200), 50, (0, 0, 255), -1)

Video Capture

Reading from a webcam.

cap = cv2.VideoCapture(0)

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

    if not ret:
        break

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

    # Break loop on 'q' key press
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

programming/python/python