opencv cheatsheet
opencv cheatsheet
Follow me on
1. cv2.imread
Reads an image from a file.
Usage:
import cv2
# Read an image
image = cv2.imread('path/to/image.jpg')
2. cv2.imwrite
Writes an image to a file.
Usage:
import cv2
# Read an image
image = cv2.imread('path/to/image.jpg')
3. cv2.imshow
Displays an image in a window.
Usage:
import cv2
# Read an image
image = cv2.imread('path/to/image.jpg')
4. cv2.cvtColor
Converts an image from one color space to another.
Usage:
import cv2
# Read an image
image = cv2.imread('path/to/image.jpg')
5. cv2.GaussianBlur
Applies a Gaussian blur to an image.
Usage:
import cv2
# Read an image
image = cv2.imread('path/to/image.jpg')
6. cv2.Canny
Applies the Canny edge detector to an image.
Usage:
import cv2
# Read an image
image = cv2.imread('path/to/image.jpg', cv2.IMREAD_GRAYSCALE)
7. cv2.HoughLines
Detects lines in a binary image using the Hough Transform.
Usage:
import cv2
import numpy as np
# Read an image
image = cv2.imread('path/to/image.jpg', cv2.IMREAD_GRAYSCALE)
8. cv2.HoughCircles
Detects circles in a binary image using the Hough Transform.
Usage:
import cv2
import numpy as np
# Read an image
image = cv2.imread('path/to/image.jpg', cv2.IMREAD_GRAYSCALE)
9. cv2.findContours
Finds contours in a binary image.
Usage:
import cv2
# Read an image
image = cv2.imread('path/to/image.jpg', cv2.IMREAD_GRAYSCALE)
# Find contours
contours, hierarchy = cv2.findContours(binary_image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
10. cv2.drawContours
Draws contours on an image.
Usage:
import cv2
# Read an image
image = cv2.imread('path/to/image.jpg', cv2.IMREAD_GRAYSCALE)
# Find contours
contours, hierarchy = cv2.findContours(binary_image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
Usage:
import cv2
# Read an image
image = cv2.imread('path/to/image.jpg')
12. cv2.circle
Draws a circle on an image.
Usage:
import cv2
# Read an image
image = cv2.imread('path/to/image.jpg')
13. cv2.line
Draws a line on an image.
Usage:
import cv2
# Read an image
image = cv2.imread('path/to/image.jpg')
14. cv2.putText
Puts text on an image.
Usage:
import cv2
# Read an image
image = cv2.imread('path/to/image.jpg')
15. cv2.resize
Resizes an image to the specified dimensions.
Usage:
import cv2
# Read an image
image = cv2.imread('path/to/image.jpg')
16. cv2.warpAffine
Applies an affine transformation to an image.
Usage:
import cv2
import numpy as np
# Read an image
image = cv2.imread('path/to/image.jpg')
17. cv2.warpPerspective
Applies a perspective transformation to an image.
Usage:
import cv2
import numpy as np
# Read an image
image = cv2.imread('path/to/image.jpg')
18. cv2.getRotationMatrix2D
Computes the affine matrix for rotating an image by a specified angle.
Usage:
import cv2
# Read an image
image = cv2.imread('path/to/image.jpg')
# Apply rotation
rotated_image = cv2.warpAffine(image, M, (image.shape[1], image.shape[0]))
Usage:
import cv2
import numpy as np
# Read an image
image = cv2.imread('path/to/image.jpg')
20. cv2.getPerspectiveTransform
Computes the perspective transformation matrix from four pairs of points.
Usage:
import cv2
import numpy as np
# Read an image
image = cv2.imread('path/to/image.jpg')
21. cv2.dilate
Applies the dilation operation to an image.
Usage:
import cv2
import numpy as np
# Read an image
image = cv2.imread('path/to/image.jpg', cv2.IMREAD_GRAYSCALE)
# Apply dilation
dilated_image = cv2.dilate(image, kernel, iterations=1)
Usage:
import cv2
import numpy as np
# Read an image
image = cv2.imread('path/to/image.jpg', cv2.IMREAD_GRAYSCALE)
# Apply erosion
eroded_image = cv2.erode(image, kernel, iterations=1)
23. cv2.morphologyEx
Applies advanced morphological transformations to an image.
Usage:
import cv2
import numpy as np
# Read an image
image = cv2.imread('path/to/image.jpg', cv2.IMREAD_GRAYSCALE)
Usage:
import cv2
# Read an image
image = cv2.imread('path/to/image.jpg', cv2.IMREAD_GRAYSCALE)
# Apply threshold
_, thresh_image = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY)
25. cv2.adaptiveThreshold
Applies an adaptive threshold to an image.
Usage:
import cv2
# Read an image
image = cv2.imread('path/to/image.jpg', cv2.IMREAD_GRAYSCALE)
26. cv2.equalizeHist
Equalizes the histogram of a grayscale image.
Usage:
import cv2
# Read an image
image = cv2.imread('path/to/image.jpg', cv2.IMREAD_GRAYSCALE)
# Equalize histogram
equalized_image = cv2.equalizeHist(image)
27. cv2.calcHist
Computes the histogram of an image.
Usage:
import cv2
import matplotlib.pyplot as plt
# Read an image
image = cv2.imread('path/to/image.jpg', cv2.IMREAD_GRAYSCALE)
# Compute histogram
hist = cv2.calcHist([image], [0], None, [256], [0, 256])
# Plot histogram
plt.plot(hist)
plt.show()
28. cv2.compareHist
Compares two histograms.
Usage:
import cv2
# Compute histograms
hist1 = cv2.calcHist([image1], [0], None, [256], [0, 256])
hist2 = cv2.calcHist([image2], [0], None, [256], [0, 256])
# Compare histograms
comparison = cv2.compareHist(hist1, hist2, cv2.HISTCMP_CORREL)
29. cv2.matchTemplate
Compares a template image with a source image using a specific method.
Usage:
import cv2
Usage:
import cv2
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
31. cv2.VideoWriter
Writes video frames to a video file.
Usage:
import cv2
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
out.write(frame)
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
out.release()
cv2.destroyAllWindows()
32. cv2.calcOpticalFlowPyrLK
Computes dense optical flow using the Lucas-Kanade method.
Usage:
import cv2
import numpy as np
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cap.release()
cv2.destroyAllWindows()
33. cv2.calcOpticalFlowFarneback
Computes dense optical flow using the Farneback method.
Usage:
import cv2
import numpy as np
while cap.isOpened():
ret, frame2 = cap.read()
if not ret:
break
next = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY)
prvs = next
cap.release()
cv2.destroyAllWindows()
34. cv2.dnn.readNet
Reads a deep learning network model from a file.
Usage:
import cv2
# Read an image
image = cv2.imread('path/to/image.jpg')
print(output)
35. cv2.dnn.blobFromImage
Converts an image to a blob for input into a deep learning network.
Usage:
import cv2
# Read an image
image = cv2.imread('path/to/image.jpg')
print(blob.shape)
36. cv2.dnn_Net.forward
Runs a forward pass of the deep learning network.
Usage:
import cv2
# Read an image
image = cv2.imread('path/to/image.jpg')
print(output)
37. cv2.CascadeClassifier
Detects objects using a cascade classifier.
Usage:
import cv2
# Read an image
image = cv2.imread('path/to/image.jpg')
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Detect faces
faces = face_cascade.detectMultiScale(gray_image, scaleFactor=1.1, minNeighbors=5)
Usage:
import cv2
# Recognize faces
# label, confidence = recognizer.predict(test_image)
39. cv2.face.FisherFaceRecognizer_create
Creates a Fisher face recognizer.
Usage:
import cv2
# Recognize faces
# label, confidence = recognizer.predict(test_image)
40. cv2.face.EigenFaceRecognizer_create
Creates an Eigen face recognizer.
Usage:
import cv2
# Recognize faces
# label, confidence = recognizer.predict(test_image)
41. cv2.bgsegm.createBackgroundSubtractorMOG
Creates a MOG background subtractor.
Usage:
import cv2
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
fg_mask = background_subtractor.apply(frame)
cap.release()
cv2.destroyAllWindows()
42. cv2.bgsegm.createBackgroundSubtractorMOG2
Creates a MOG2 background subtractor.
Usage:
import cv2
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
fg_mask = background_subtractor.apply(frame)
cap.release()
cv2.destroyAllWindows()
43. cv2.bgsegm.createBackgroundSubtractorKNN
Creates a KNN background subtractor.
Usage:
import cv2
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
fg_mask = background_subtractor.apply(frame)
cap.release()
cv2.destroyAllWindows()
44. cv2.bgsegm.createBackgroundSubtractorGMG
Creates a GMG background subtractor.
Usage:
import cv2
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
fg_mask = background_subtractor.apply(frame)
cap.release()
cv2.destroyAllWindows()
45. cv2.FastFeatureDetector_create
Creates a FAST feature detector.
Usage:
import cv2
# Read an image
image = cv2.imread('path/to/image.jpg', cv2.IMREAD_GRAYSCALE)
# Detect keypoints
keypoints = fast.detect(image, None)
# Draw keypoints
image_with_keypoints = cv
46. cv2.ORB_create
Creates an ORB feature detector and descriptor extractor.
Usage:
import cv2
# Read an image
image = cv2.imread('path/to/image.jpg', cv2.IMREAD_GRAYSCALE)
# Draw keypoints
image_with_keypoints = cv2.drawKeypoints(image, keypoints, None, color=(255, 0, 0))
Usage:
import cv2
# Read an image
image = cv2.imread('path/to/image.jpg', cv2.IMREAD_GRAYSCALE)
# Draw keypoints
image_with_keypoints = cv2.drawKeypoints(image, keypoints, None, color=(255, 0, 0))
48. cv2.SURF_create
Creates a SURF feature detector and descriptor extractor.
Usage:
import cv2
# Read an image
image = cv2.imread('path/to/image.jpg', cv2.IMREAD_GRAYSCALE)
# Draw keypoints
image_with_keypoints = cv2.drawKeypoints(image, keypoints, None, color=(255, 0, 0))
49. cv2.BRISK_create
Creates a BRISK feature detector and descriptor extractor.
Usage:
import cv2
# Read an image
image = cv2.imread('path/to/image.jpg', cv2.IMREAD_GRAYSCALE)
# Draw keypoints
image_with_keypoints = cv2.drawKeypoints(image, keypoints, None, color=(255, 0, 0))
Usage:
import cv2
# Read an image
image = cv2.imread('path/to/image.jpg', cv2.IMREAD_GRAYSCALE)
# Detect keypoints
keypoints = orb.detect(image, None)
# Draw keypoints
image_with_keypoints = cv2.drawKeypoints(image, keypoints, None, color=(255, 0, 0))
import cv2
# Load YOLO
net = cv2.dnn.readNet("yolov3.weights", "yolov3.cfg")
layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
# Load image
img = cv2.imread("image.jpg")
height, width, channels = img.shape
# Detecting objects
blob = cv2.dnn.blobFromImage(img, 0.00392, (416, 416), (0, 0, 0), True, crop=False)
net.setInput(blob)
outs = net.forward(output_layers)
# Rectangle coordinates
x = int(center_x - w / 2)
y = int(center_y - h / 2)
boxes.append([x, y, w, h])
confidences.append(float(confidence))
class_ids.append(class_id)
cv2.imshow("Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
import cv2
# Load image
image = cv2.imread("image.jpg")
import cv2
import mediapipe as mp
mp_hands = mp.solutions.hands
mp_drawing = mp.solutions.drawing_utils
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
cap.release()
cv2.destroyAllWindows()
Use Case 4: Image Recognition using InceptionV3
import cv2
# Load image
image = cv2.imread("image.jpg")
import cv2
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
# Detect faces
faces = face_cascade.detectMultiScale(gray_frame, scaleFactor=1.1, minNeighbors=5)
cap.release()
cv2.destroyAllWindows()
Use Case 6: Real-time Object Tracking using GOTURN Tracker
import cv2
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
cap.release()
cv2.destroyAllWindows()
Use Case 7: Background Subtraction using KNN
import cv2
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
cap.release()
cv2.destroyAllWindows()
Use Case 8: Lane Detection in a Video
import cv2
import numpy as np
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
cap.release()
cv2.destroyAllWindows()
Use Case 9: Real-time Face Recognition using LBPH
import cv2
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
# Detect faces
faces = face_cascade.detectMultiScale(gray_frame, scaleFactor=1.1, minNeighbors=5)
cap.release()
cv2.destroyAllWindows()
Use Case 10: Real-time Emotion Detection using FER2013
import cv2
import numpy as np
from keras.models import load_model
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
# Detect faces
faces = face_cascade.detectMultiScale(gray_frame, scaleFactor=1.1, minNeighbors=5)
cap.release()
cv2.destroyAllWindows()
Use Case 11: Road Sign Detection using HOG and SVM
import cv2
# Load image
image = cv2.imread('road_sign.jpg')
# Display result
if result[1][0] == 1:
cv2.putText(image, 'Road Sign Detected', (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
import cv2
import numpy as np
net.setInput(blob2)
output2 = net.forward()
import cv2
# Load image
image = cv2.imread('scene_text.jpg')
orig = image.copy()
(H, W) = image.shape[:2]
import cv2
import numpy as np
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
# Detect faces
faces = face_cascade.detectMultiScale(gray_frame, scaleFactor=1.1, minNeighbors=5)
cap.release()
cv2.destroyAllWindows()
Use Case 15: Image Inpainting using Deep Learning
import cv2
import numpy as np
# Perform inpainting
output = net.forward()
import cv2
import pytesseract
# Load image
image = cv2.imread('document.jpg')
# Apply thresholding
_, thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY_INV)
# Apply dilation
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
dilated = cv2.dilate(thresh, kernel, iterations=1)
import cv2
import dlib
from scipy.spatial import distance
def eye_aspect_ratio(eye):
A = distance.euclidean(eye[1], eye[5])
B = distance.euclidean(eye[2], eye[4])
C = distance.euclidean(eye[0], eye[3])
ear = (A + B) / (2.0 * C)
return ear
# Define thresholds
EYE_AR_THRESH = 0.3
EYE_AR_CONSEC_FRAMES = 48
# Initialize counters
counter = 0
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
left_ear = eye_aspect_ratio(left_eye)
right_ear = eye_aspect_ratio(right_eye)
ear = (left_ear + right_ear) / 2.0
cap.release()
cv2.destroyAllWindows()
Use Case 18: Real-time Fire Detection using Color Thresholding
import cv2
import numpy as np
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
cap.release()
cv2.destroyAllWindows()
Use Case 19: Real-time Smoke Detection using Color and Motion
import cv2
import numpy as np
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
cap.release()
cv2.destroyAllWindows()
Use Case 20: Real-time Vehicle Detection using HOG and SVM
import cv2
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
cap.release()
cv2.destroyAllWindows()
Follow me on