opencv cheatsheet
opencv cheatsheet
opencv cheatsheet
Follow me on
1. cv2.imrea
d
Reads an image from a file.
Usage:
import
cv2
# Read an image
image =
cv2.imread('path/to/image.jpg')
2. cv2.imwrit
e
Writes an image to a file.
Usage:
import
cv2
# Read an image
image =
cv2.imread('path/to/image.jpg')
3. cv2.imsho
w
Displays an image in a window.
Usage:
import
cv2
# Read an image
image =
cv2.imread('path/to/image.jpg')
4. cv2.cvtColo
r
Converts an image from one color space to another.
Usage:
import
cv2
# Read an image
image =
cv2.imread('path/to/image.jpg')
5. cv2.GaussianBlu
r
Applies a Gaussian blur to an image.
Usage:
import
cv2
# Read an image
image =
cv2.imread('path/to/image.jpg')
6. cv2.Cann
y
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.HoughLine
s
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.HoughCircle
s
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.findContour
s
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.drawContour
s
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.circl
e
Draws a circle on an image.
Usage:
import
cv2
# Read an image
image =
cv2.imread('path/to/image.jpg')
13. cv2.lin
e
Draws a line on an image.
Usage:
import
cv2
# Read an image
image =
cv2.imread('path/to/image.jpg')
14. cv2.putTex
t
Puts text on an image.
Usage:
import
cv2
# Read an image
image =
cv2.imread('path/to/image.jpg')
15. cv2.resiz
e
Resizes an image to the specified dimensions.
Usage:
import
cv2
# Read an image
image =
cv2.imread('path/to/image.jpg')
16. cv2.warpAffin
e
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.warpPerspecti
ve
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.getRotationMatrix
2D
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.getPerspectiveTransfo
rm
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')
# Apply perspective
transformation
transformed_image = cv2
.warpPerspective(image, M, (image.shape[1],
image.shape[0]))
21. cv2.dilat
e
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.morphologyE
x
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.adaptiveThresho
ld
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.equalizeHis
t
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.calcHis
t
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.compareHis
t
Compares two histograms.
Usage:
import
cv2
# Compare histograms
comparison = cv2.compareHist(hist1, hist2,
cv2.HISTCMP_CORREL)
29. cv2.matchTemplat
e
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.VideoWrite
r
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.calcOpticalFlowPyr
LK
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.calcOpticalFlowFarneba
ck
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.readNe
t
Reads a deep learning network model from a file.
Usage:
import
cv2
# Read an image
image =
cv2.imread('path/to/image.jpg')
# Perform forward
pass
output =
print(output
)
35. cv2.dnn.blobFromIma
ge
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.forwa
rd
Runs a forward pass of the deep learning network.
Usage:
import
cv2
# Read an image
image =
cv2.imread('path/to/image.jpg')
# Perform forward
pass
output =
print(output
)
37. cv2.CascadeClassifi
er
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_cre
ate
Creates a Fisher face recognizer.
Usage:
import
cv2
# Recognize faces
# label, confidence =
recognizer.predict(test_image)
40. cv2.face.EigenFaceRecognizer_cre
ate
Creates an Eigen face recognizer.
Usage:
import
cv2
# Recognize faces
# label, confidence =
recognizer.predict(test_image)
41. cv2.bgsegm.createBackgroundSubtractor
MOG
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)
cv2.imshow('Foreground Mask',
fg_mask)
if cv2.waitKey(1) & 0xFF ==
ord('q'): break
cap.release()
cv2.destroyAllWindows
()
42. cv2.bgsegm.createBackgroundSubtractorM
OG2
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)
cv2.imshow('Foreground Mask',
fg_mask)
if cv2.waitKey(1) & 0xFF ==
ord('q'): break
cap.release()
cv2.destroyAllWindows
()
43. cv2.bgsegm.createBackgroundSubtractor
KNN
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)
cv2.imshow('Foreground Mask',
fg_mask)
if cv2.waitKey(1) & 0xFF ==
ord('q'): break
cap.release()
cv2.destroyAllWindows
()
44. cv2.bgsegm.createBackgroundSubtractor
GMG
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)
cv2.imshow('Foreground Mask',
fg_mask)
if cv2.waitKey(1) & 0xFF ==
ord('q'): break
cap.release()
cv2.destroyAllWindows
()
45. cv2.FastFeatureDetector_crea
te
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_creat
e
Creates an ORB feature detector and descriptor extractor.
Usage:
import
cv2
# Create an ORB
detector
orb = cv2.ORB_create()
# 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
# Create a SIFT
detector
sift =
# 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_creat
e
Creates a SURF feature detector and descriptor extractor.
Usage:
import
cv2
# Create a SURF
detector
surf =
# 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_creat
e
Creates a BRISK feature detector and descriptor extractor.
Usage:
import
cv2
# Create a BRISK
detector
brisk =
# 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)
# Create a feature
detector
orb = cv2.ORB_create()
# 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")
# Perform forward
pass output =
net.forward()
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")
# Perform forward
pass
output =
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:
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)
for (x, y, w, h) in
faces: # Recognize
the face
label, confidence = recognizer.predict(gray_frame[y:y+h, x:x+w])
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]
for x in range(0,
num_cols): if
scores_data[x] < 0.5:
continue
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)
print('Extracted Text:',
text)
Use Case 17: Real-time Drowsiness Detection using Eye Aspect
Ratio
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
gray = cv2.cvtColor(frame,
cv2.COLOR_BGR2GRAY) faces = detector(gray)
left_ear = eye_aspect_ratio(left_eye)
right_ear = eye_aspect_ratio(right_eye)
ear = (left_ear + right_ear) /
2.0
cv2.imshow('Drowsiness Detection',
frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
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