Language: Python
ML/AI
OpenCV (Open Source Computer Vision Library) was initially developed by Intel in 1999. OpenCV-Python provides bindings to access the full power of OpenCV in Python, making it popular for real-time image and video processing, machine learning, and robotics applications.
OpenCV-Python is a Python wrapper for the OpenCV C++ library, providing tools for computer vision, image processing, and video analysis. It allows rapid prototyping and deployment of vision applications in Python.
pip install opencv-pythonconda install -c conda-forge opencvOpenCV-Python provides functions for image I/O, color space conversions, filtering, transformations, object detection, and machine learning integration. It supports reading and writing images and videos, as well as performing operations on arrays representing images.
import cv2
img = cv2.imread('image.jpg')
cv2.imshow('Image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()Reads an image from file and displays it in a window until any key is pressed.
import cv2
img = cv2.imread('image.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow('Gray', gray)
cv2.waitKey(0)
cv2.destroyAllWindows()Converts a color image to grayscale using OpenCV’s color conversion function.
import cv2
img = cv2.imread('image.jpg', 0)
edges = cv2.Canny(img, 100, 200)
cv2.imshow('Edges', edges)
cv2.waitKey(0)
cv2.destroyAllWindows()Detects edges in a grayscale image using the Canny algorithm.
import cv2
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
cv2.imshow('Webcam', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()Captures video from the default webcam and displays it in real-time.
import cv2
import numpy as np
img = np.zeros((512,512,3), np.uint8)
cv2.line(img, (0,0), (511,511), (255,0,0), 5)
cv2.rectangle(img, (100,100), (300,300), (0,255,0), 3)
cv2.circle(img, (256,256), 50, (0,0,255), -1)
cv2.imshow('Shapes', img)
cv2.waitKey(0)
cv2.destroyAllWindows()Draws lines, rectangles, and circles on an empty image using OpenCV drawing functions.
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
img = cv2.imread('group.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
cv2.imshow('Faces', img)
cv2.waitKey(0)
cv2.destroyAllWindows()Detects faces in an image using pre-trained Haar cascade classifiers.
Use NumPy arrays for image processing to leverage vectorized operations.
Release video capture objects and destroy windows to avoid resource leaks.
Use proper color conversion codes when changing image color spaces.
Profile and optimize processing pipelines for real-time applications.
Keep pre-trained classifiers and models organized for reuse.