Page 1 of 9
Table of Contents
OpenCV Python Image Processing Cheat Sheet
1. Installation
2. Read, Write, and Display Images
3. Resize & Crop
4. Convert Color Spaces
5. Drawing Shapes
6. Image Thresholding
7. Blurring & Smoothing
8. Edge Detection
9. Morphological Operations
10. Contours Detection
11. Object Detection with Haar Cascades
12. Perspective Transformation
13. Histogram Equalization
14. Bitwise Operations
15. Template Matching
16. Optical Flow (Motion Tracking)
17. Video Capture & Processing
18. Background Subtraction
19. Image Translation (Shifting)
20. Image Rotation
OpenCV Python Image Processing Cheat Sheet
Make me a cheetsheet on opencv py for image proccessing
Page 2 of 9
Here's a cheat sheet for OpenCV (Python) for image processing covering the most common operations:
OpenCV Python Image Processing Cheat
Sheet
1. Installation
bash
pip install opencv-python numpy
python
import cv2
import numpy as np
2. Read, Write, and Display Images
python
img = cv2.imread('image.jpg') # Read image
cv2.imshow('Image', img) # Display image
cv2.waitKey(0) # Wait for key press
cv2.destroyAllWindows() # Close window
cv2.imwrite('output.jpg', img) # Save image
3. Resize & Crop
python
resized = cv2.resize(img, (300, 300)) # Resize to 300x300
cropped = img[50:200, 100:300] # Crop ROI (y1:y2, x1:x2)
4. Convert Color Spaces
python
Page 3 of 9
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Convert to grayscale
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # Convert to HSV
lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB) # Convert to LAB
5. Drawing Shapes
python
cv2.line(img, (50, 50), (200, 50), (0, 255, 0), 3) # Line
cv2.rectangle(img, (50, 50), (200, 200), (255, 0, 0), 2) # Rectangle
cv2.circle(img, (150, 150), 50, (0, 0, 255), -1) # Filled Circle
cv2.putText(img, 'OpenCV', (50, 250), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 255), 2)
6. Image Thresholding
python
_, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY) # Simple Threshold
adaptive = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY, 11, 2) # Adaptive Threshold
7. Blurring & Smoothing
python
blurred = cv2.GaussianBlur(img, (5, 5), 0) # Gaussian Blur
median = cv2.medianBlur(img, 5) # Median Blur
bilateral = cv2.bilateralFilter(img, 9, 75, 75) # Bilateral Filtering
8. Edge Detection
python
edges = cv2.Canny(gray, 50, 150) # Canny Edge Detection
9. Morphological Operations
Page 4 of 9
python
kernel = np.ones((5, 5), np.uint8)
dilated = cv2.dilate(binary, kernel, iterations=1) # Dilation
eroded = cv2.erode(binary, kernel, iterations=1) # Erosion
opened = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel) # Opening (erosion + dilation)
closed = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kernel) # Closing (dilation + erosion)
10. Contours Detection
python
contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, contours, -1, (0, 255, 0), 2) # Draw all contours
11. Object Detection with Haar Cascades
python
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
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)
12. Perspective Transformation
python
pts1 = np.float32([[50, 50], [200, 50], [50, 200], [200, 200]])
pts2 = np.float32([[10, 100], [180, 50], [50, 250], [220, 220]])
matrix = cv2.getPerspectiveTransform(pts1, pts2)
transformed = cv2.warpPerspective(img, matrix, (300, 300))
13. Histogram Equalization
python
equalized = cv2.equalizeHist(gray)
14. Bitwise Operations
Page 5 of 9
python
bitwise_and = cv2.bitwise_and(img1, img2)
bitwise_or = cv2.bitwise_or(img1, img2)
bitwise_xor = cv2.bitwise_xor(img1, img2)
bitwise_not = cv2.bitwise_not(img1)
15. Template Matching
python
template = cv2.imread('template.jpg', 0)
res = cv2.matchTemplate(gray, template, cv2.TM_CCOEFF_NORMED)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
top_left = max_loc
bottom_right = (top_left[0] + template.shape[1], top_left[1] + template.shape[0])
cv2.rectangle(img, top_left, bottom_right, (0, 255, 0), 2)
16. Optical Flow (Motion Tracking)
python
old_gray = cv2.cvtColor(prev_frame, cv2.COLOR_BGR2GRAY)
new_gray = cv2.cvtColor(curr_frame, cv2.COLOR_BGR2GRAY)
flow = cv2.calcOpticalFlowFarneback(old_gray, new_gray, None, 0.5, 3, 15, 3, 5, 1.2, 0)
17. Video Capture & Processing
python
cap = cv2.VideoCapture(0) # Capture from webcam
while True:
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('Video', gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
18. Background Subtraction
Page 6 of 9
python
fgbg = cv2.createBackgroundSubtractorMOG2()
fgmask = fgbg.apply(frame)
19. Image Translation (Shifting)
python
M = np.float32([[1, 0, 100], [0, 1, 50]])
shifted = cv2.warpAffine(img, M, (img.shape[1], img.shape[0]))
20. Image Rotation
python
(h, w) = img.shape[:2]
center = (w // 2, h // 2)
M = cv2.getRotationMatrix2D(center, 45, 1.0) # Rotate by 45 degrees
rotated = cv2.warpAffine(img, M, (w, h))
This cheat sheet should help you quickly reference image processing techniques using OpenCV in
Python! Let me know if you need any specific implementations.
Ummm nice actually... Now this time in a tabular format with all
the details like what the purpose
Here's your OpenCV Python Image Processing Cheat Sheet in a tabular format, including the
operation, purpose, and example code for easy reference.
OpenCV Python Image Processing Cheat Sheet
Operation Purpose Example Code
Install OpenCV Install OpenCV and pip install opencv-python numpy
NumPy for image
Page 7 of 9
Operation Purpose Example Code
processing
Read an Image Load an image from file img = cv2.imread('image.jpg')
Display an Image Show the loaded image cv2.imshow('Image', img); cv2.waitKey(0);
in a window cv2.destroyAllWindows()
Save an Image Save an image to a file cv2.imwrite('output.jpg', img)
Resize an Image Change image resized = cv2.resize(img, (300, 300))
dimensions
Crop an Image Extract a region of cropped = img[50:200, 100:300]
interest (ROI)
Convert to Grayscale Convert an image to gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
black and white
Convert to HSV Convert image to HSV hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
color space
Draw a Line Draw a straight line on cv2.line(img, (50,50), (200,50), (0,255,0), 3)
an image
Draw a Rectangle Draw a rectangle cv2.rectangle(img, (50,50), (200,200), (255,0,0), 2)
(bounding box)
Draw a Circle Draw a filled or outlined cv2.circle(img, (150,150), 50, (0,0,255), -1)
circle
Write Text on Image Overlay text on an image cv2.putText(img, 'OpenCV', (50,250), cv2.FONT_HERSHEY_SIMPLEX,
1, (0,255,255), 2)
Simple Thresholding Convert grayscale image _, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
to binary
Adaptive Adjust threshold adaptive = cv2.adaptiveThreshold(gray, 255,
Thresholding dynamically cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)
Gaussian Blur Reduce noise and blurred = cv2.GaussianBlur(img, (5,5), 0)
smooth an image
Median Blur Remove salt-and-pepper median = cv2.medianBlur(img, 5)
noise
Bilateral Filter Preserve edges while bilateral = cv2.bilateralFilter(img, 9, 75, 75)
blurring
Edge Detection Detect edges in an image edges = cv2.Canny(gray, 50, 150)
(Canny)
Page 8 of 9
Operation Purpose Example Code
Dilation Expand white regions in dilated = cv2.dilate(binary, np.ones((5,5), np.uint8), iterations=1)
an image
Erosion Shrink white regions in eroded = cv2.erode(binary, np.ones((5,5), np.uint8), iterations=1)
an image
Find Contours Detect objects in an contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL,
image cv2.CHAIN_APPROX_SIMPLE)
Draw Contours Highlight detected cv2.drawContours(img, contours, -1, (0,255,0), 2)
contours
Face Detection Detect faces using Haar faces = face_cascade.detectMultiScale(gray, 1.3, 5)
cascades
Perspective Warp an image to a new transformed = cv2.warpPerspective(img, matrix, (300,300))
Transformation perspective
Histogram Improve contrast in equalized = cv2.equalizeHist(gray)
Equalization grayscale images
Bitwise AND Perform AND operation bitwise_and = cv2.bitwise_and(img1, img2)
on two images
Bitwise OR Perform OR operation on bitwise_or = cv2.bitwise_or(img1, img2)
two images
Template Matching Detect object locations in res = cv2.matchTemplate(gray, template,
an image cv2.TM_CCOEFF_NORMED)
Optical Flow (Motion Detect motion between flow = cv2.calcOpticalFlowFarneback(old_gray, new_gray, None,
Tracking) frames 0.5, 3, 15, 3, 5, 1.2, 0)
Open Webcam Video Capture video from the cap = cv2.VideoCapture(0)
webcam
Display Video Feed Show video frame-by- cv2.imshow('Video', frame)
frame
Background Detect foreground fgmask = fgbg.apply(frame)
Subtraction objects
Translate Image Move an image up/down shifted = cv2.warpAffine(img, M, (img.shape[1], img.shape[0]))
(Shift Position) or left/right
Rotate Image Rotate an image by any rotated = cv2.warpAffine(img, M, (w, h))
angle
Page 9 of 9
This table provides a quick reference to OpenCV's key functions for image processing. Let me know if
you need further details or modifications!