Make sure OpenCV is installed first:
pip install opencv-python. See Python install guide if you get import errors.Images
Read, display and write images
import cv2
# Read an image (BGR format by default):
img = cv2.imread(r"C:\path\to\image.jpg")
# Show in a window (press any key to close):
cv2.imshow("Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
# Convert BGR to RGB (for matplotlib):
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# Save image:
cv2.imwrite(r"C:\output.png", img)
Camera capture
Capture from webcam
import cv2
# Open default camera (index 0):
cap = cv2.VideoCapture(0)
# If camera fails, try DirectShow backend:
cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
while cap.isOpened():
ret, frame = cap.read()
if not ret: break
cv2.imshow("Camera", frame)
if cv2.waitKey(1) & 0xFF == ord('q'): break
cap.release()
cv2.destroyAllWindows()
Press q to quit. If the camera does not open, see VideoCapture issues guide.
Video files
Read and write video files
import cv2
# Read a video file:
cap = cv2.VideoCapture(r"C:\video.mp4")
fps = cap.get(cv2.CAP_PROP_FPS)
w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
# Write output video (mp4v codec):
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter('out.mp4', fourcc, fps, (w, h))
Basic operations
Common image operations
import cv2
# Resize:
resized = cv2.resize(img, (640, 480))
# Grayscale:
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Blur:
blurred = cv2.GaussianBlur(img, (15, 15), 0)
# Edge detection:
edges = cv2.Canny(gray, 100, 200)
# Draw rectangle:
cv2.rectangle(img, (10,10), (200,200), (0,255,0), 2)
FAQ
Quickstart questions
cv2.imread() returns None
The file path is wrong or the file does not exist. Use raw strings or forward slashes:
cv2.imread(r"C:\Users\name\image.jpg") or cv2.imread("C:/Users/name/image.jpg"). Check that the file extension is correct and the file is not corrupted.cv2.imshow() window appears and closes immediately
You need
cv2.waitKey(0) after imshow(). Without it, the window is created and destroyed in the same frame. Add cv2.waitKey(0) to pause until a key is pressed, then cv2.destroyAllWindows() to clean up.How to use OpenCV with matplotlib?
OpenCV uses BGR color order, matplotlib uses RGB. Convert before displaying:
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) then plt.imshow(img_rgb).