Learn OPENCV with Real Code Examples
Updated Nov 24, 2025
Code Sample Descriptions
1
OpenCV Simple Image Read and Display
import cv2
img = cv2.imread('example.jpg')
cv2.imshow('Image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
A minimal OpenCV example reading an image and displaying it in a window.
2
OpenCV Convert Image to Grayscale
import cv2
img = cv2.imread('example.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow('Gray Image', gray)
cv2.waitKey(0)
cv2.destroyAllWindows()
Reads an image and converts it to grayscale.
3
OpenCV Resize Image
import cv2
img = cv2.imread('example.jpg')
resized = cv2.resize(img,(200,200))
cv2.imshow('Resized', resized)
cv2.waitKey(0)
cv2.destroyAllWindows()
Resizes an image to a specific width and height.
4
OpenCV Draw Shapes on Image
import cv2
import numpy as np
img = np.zeros((300,300,3), dtype=np.uint8)
cv2.rectangle(img,(50,50),(250,250),(0,255,0),2)
cv2.circle(img,(150,150),50,(255,0,0),2)
cv2.line(img,(0,0),(300,300),(0,0,255),2)
cv2.imshow('Shapes', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Draws rectangle, circle, and line on an image.
5
OpenCV Image Thresholding
import cv2
img = cv2.imread('example.jpg',0)
_,thresh = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
cv2.imshow('Threshold', thresh)
cv2.waitKey(0)
cv2.destroyAllWindows()
Applies binary thresholding to a grayscale image.
6
OpenCV Edge Detection
import cv2
img = cv2.imread('example.jpg',0)
edges = cv2.Canny(img,100,200)
cv2.imshow('Edges', edges)
cv2.waitKey(0)
cv2.destroyAllWindows()
Detects edges using the Canny algorithm.
7
OpenCV Video Capture
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 webcam and displays it.
8
OpenCV Image Blurring
import cv2
img = cv2.imread('example.jpg')
blur = cv2.GaussianBlur(img,(5,5),0)
cv2.imshow('Blurred', blur)
cv2.waitKey(0)
cv2.destroyAllWindows()
Applies Gaussian blur to an image.
9
OpenCV Face Detection with Haar Cascades
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
img = cv2.imread('face.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 Haar cascades.
10
OpenCV Video Frame Processing
import cv2
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('Gray Video', gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
Processes video frame by frame and converts to grayscale.