Pre-built Python bindings for OpenCV, the comprehensive open-source computer vision and image processing library with 2500+ algorithms
OpenCV provides high-level GUI capabilities for displaying images, creating interactive windows, and drawing shapes on images. These features are essential for debugging, visualization, and creating interactive computer vision applications.
Important Note: GUI functions are not available in headless packages (opencv-python-headless). If you're running OpenCV in a server environment or headless system, these functions will not work. Use the standard opencv-python package if you need GUI functionality.
OpenCV provides a complete set of functions for creating and managing display windows.
# Display image in a window
cv2.imshow(winname, mat) -> NoneShows an image in the specified window. If the window doesn't exist, it will be created with WINDOW_AUTOSIZE flag. The window will automatically fit the image size.
Parameters:
winname (str): Name of the windowmat (np.ndarray): Image to displayExample:
import cv2
import numpy as np
img = cv2.imread('image.jpg')
cv2.imshow('My Image', img)
cv2.waitKey(0) # Wait for key press
cv2.destroyAllWindows()# Create a named window
cv2.namedWindow(winname, flags=cv2.WINDOW_AUTOSIZE) -> NoneCreates a window that can be used as a placeholder for images and trackbars. Created windows are referred to by their names.
Parameters:
winname (str): Name of the windowflags (int): Window flags (see Window Flags section)Example:
# Create a resizable window
cv2.namedWindow('My Window', cv2.WINDOW_NORMAL)
cv2.imshow('My Window', img)# Destroy specific window
cv2.destroyWindow(winname) -> NoneDestroys the specified window.
Parameters:
winname (str): Name of the window to destroy# Destroy all windows
cv2.destroyAllWindows() -> NoneDestroys all HighGUI windows. Should be called at the end of GUI applications.
# Wait for key press
cv2.waitKey(delay=0) -> intWaits for a key press for a specified number of milliseconds. This function is essential for GUI event processing.
Parameters:
delay (int): Delay in milliseconds. 0 means wait indefinitelyReturns:
Example:
# Wait indefinitely for key press
key = cv2.waitKey(0)
if key == ord('q'):
print("Q was pressed")
elif key == 27: # ESC key
print("ESC was pressed")
# Wait 30ms (useful for video playback)
key = cv2.waitKey(30)# Poll for key press (non-blocking)
cv2.pollKey() -> intPolls for a key press without blocking. Similar to waitKey(0) but non-blocking.
Returns:
# Resize window
cv2.resizeWindow(winname, width, height) -> NoneResizes the window to the specified size. The window must have been created with WINDOW_NORMAL flag.
Parameters:
winname (str): Name of the windowwidth (int): New window widthheight (int): New window height# Move window
cv2.moveWindow(winname, x, y) -> NoneMoves the window to the specified position.
Parameters:
winname (str): Name of the windowx (int): New x-coordinate of the top-left cornery (int): New y-coordinate of the top-left corner# Get window property
cv2.getWindowProperty(winname, prop_id) -> floatGets a property of the window.
Parameters:
winname (str): Name of the windowprop_id (int): Property identifierReturns:
# Set window property
cv2.setWindowProperty(winname, prop_id, prop_value) -> NoneSets a property of the window.
Parameters:
winname (str): Name of the windowprop_id (int): Property identifierprop_value (float): New property value# Set window title
cv2.setWindowTitle(winname, title) -> NoneUpdates the window title.
Parameters:
winname (str): Name of the windowtitle (str): New window titleConstants for window creation:
cv2.WINDOW_NORMAL # User can resize the window
cv2.WINDOW_AUTOSIZE # Window size automatically adjusted to fit image
cv2.WINDOW_FULLSCREEN # Window is in fullscreen mode
cv2.WINDOW_FREERATIO # Window can be resized without maintaining aspect ratio
cv2.WINDOW_KEEPRATIO # Window maintains aspect ratio when resized
cv2.WINDOW_GUI_EXPANDED # Window with extended GUI features
cv2.WINDOW_GUI_NORMAL # Window with basic GUI featuresTrackbars provide an interactive way to adjust parameters in real-time. They are useful for tuning algorithms and exploring parameter spaces.
# Create trackbar
cv2.createTrackbar(trackbarname, winname, value, count, onChange) -> NoneCreates a trackbar and attaches it to the specified window.
Parameters:
trackbarname (str): Name of the trackbarwinname (str): Name of the window that will be the parent of the trackbarvalue (int): Initial trackbar positioncount (int): Maximum trackbar position (minimum is always 0)onChange (callable): Callback function called when trackbar value changes. Signature: onChange(value: int) -> NoneExample:
def on_threshold_change(value):
_, thresh = cv2.threshold(gray, value, 255, cv2.THRESH_BINARY)
cv2.imshow('Threshold', thresh)
cv2.namedWindow('Threshold')
cv2.createTrackbar('Threshold', 'Threshold', 127, 255, on_threshold_change)# Get trackbar position
cv2.getTrackbarPos(trackbarname, winname) -> intGets the current position of the trackbar.
Parameters:
trackbarname (str): Name of the trackbarwinname (str): Name of the parent windowReturns:
# Set trackbar position
cv2.setTrackbarPos(trackbarname, winname, pos) -> NoneSets the trackbar position.
Parameters:
trackbarname (str): Name of the trackbarwinname (str): Name of the parent windowpos (int): New trackbar position# Set trackbar minimum value
cv2.setTrackbarMin(trackbarname, winname, minval) -> NoneSets the minimum value of the trackbar.
Parameters:
trackbarname (str): Name of the trackbarwinname (str): Name of the parent windowminval (int): New minimum value# Set trackbar maximum value
cv2.setTrackbarMax(trackbarname, winname, maxval) -> NoneSets the maximum value of the trackbar.
Parameters:
trackbarname (str): Name of the trackbarwinname (str): Name of the parent windowmaxval (int): New maximum valueExample - Multiple Trackbars:
import cv2
import numpy as np
def nothing(x):
pass
# Create window and trackbars
cv2.namedWindow('Color Picker')
cv2.createTrackbar('R', 'Color Picker', 0, 255, nothing)
cv2.createTrackbar('G', 'Color Picker', 0, 255, nothing)
cv2.createTrackbar('B', 'Color Picker', 0, 255, nothing)
while True:
# Get current trackbar positions
r = cv2.getTrackbarPos('R', 'Color Picker')
g = cv2.getTrackbarPos('G', 'Color Picker')
b = cv2.getTrackbarPos('B', 'Color Picker')
# Create image with selected color
img = np.zeros((300, 512, 3), np.uint8)
img[:] = [b, g, r]
cv2.imshow('Color Picker', img)
if cv2.waitKey(1) & 0xFF == 27: # ESC to exit
break
cv2.destroyAllWindows()OpenCV allows you to capture and handle mouse events in windows, enabling interactive applications.
# Set mouse callback function
cv2.setMouseCallback(windowName, onMouse, param=None) -> NoneSets a mouse event callback function for the specified window.
Parameters:
windowName (str): Name of the windowonMouse (callable): Callback function with signature: onMouse(event, x, y, flags, param)
event (int): Mouse event type (see Mouse Event Constants)x (int): X-coordinate of the mouse eventy (int): Y-coordinate of the mouse eventflags (int): Event flags (see Mouse Event Flags)param: User data passed to the callbackparam: Optional user data to pass to the callbackExample:
def mouse_callback(event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONDOWN:
print(f"Left button clicked at ({x}, {y})")
elif event == cv2.EVENT_MOUSEMOVE:
if flags & cv2.EVENT_FLAG_LBUTTON:
print(f"Drawing at ({x}, {y})")
elif event == cv2.EVENT_RBUTTONDOWN:
print(f"Right button clicked at ({x}, {y})")
img = np.zeros((512, 512, 3), np.uint8)
cv2.namedWindow('Mouse Events')
cv2.setMouseCallback('Mouse Events', mouse_callback)
while True:
cv2.imshow('Mouse Events', img)
if cv2.waitKey(20) & 0xFF == 27:
break
cv2.destroyAllWindows()Constants representing different mouse events:
cv2.EVENT_MOUSEMOVE # Mouse moved
cv2.EVENT_LBUTTONDOWN # Left button pressed
cv2.EVENT_RBUTTONDOWN # Right button pressed
cv2.EVENT_MBUTTONDOWN # Middle button pressed
cv2.EVENT_LBUTTONUP # Left button released
cv2.EVENT_RBUTTONUP # Right button released
cv2.EVENT_MBUTTONUP # Middle button released
cv2.EVENT_LBUTTONDBLCLK # Left button double-clicked
cv2.EVENT_RBUTTONDBLCLK # Right button double-clicked
cv2.EVENT_MBUTTONDBLCLK # Middle button double-clicked
cv2.EVENT_MOUSEWHEEL # Mouse wheel scrolled (vertical)
cv2.EVENT_MOUSEHWHEEL # Mouse wheel scrolled (horizontal)Constants representing modifier keys and button states during mouse events:
cv2.EVENT_FLAG_LBUTTON # Left button is pressed
cv2.EVENT_FLAG_RBUTTON # Right button is pressed
cv2.EVENT_FLAG_MBUTTON # Middle button is pressed
cv2.EVENT_FLAG_CTRLKEY # Ctrl key is pressed
cv2.EVENT_FLAG_SHIFTKEY # Shift key is pressed
cv2.EVENT_FLAG_ALTKEY # Alt key is pressedExample - Drawing Application:
import cv2
import numpy as np
drawing = False # True if mouse is pressed
mode = True # True for rectangle, False for circle
ix, iy = -1, -1
def draw_shape(event, x, y, flags, param):
global ix, iy, drawing, mode
if event == cv2.EVENT_LBUTTONDOWN:
drawing = True
ix, iy = x, y
elif event == cv2.EVENT_MOUSEMOVE:
if drawing:
if mode:
cv2.rectangle(img, (ix, iy), (x, y), (0, 255, 0), -1)
else:
cv2.circle(img, (x, y), 5, (0, 0, 255), -1)
elif event == cv2.EVENT_LBUTTONUP:
drawing = False
if mode:
cv2.rectangle(img, (ix, iy), (x, y), (0, 255, 0), -1)
else:
cv2.circle(img, (x, y), 5, (0, 0, 255), -1)
img = np.zeros((512, 512, 3), np.uint8)
cv2.namedWindow('Drawing')
cv2.setMouseCallback('Drawing', draw_shape)
while True:
cv2.imshow('Drawing', img)
k = cv2.waitKey(1) & 0xFF
if k == ord('m'):
mode = not mode # Toggle mode
elif k == 27:
break
cv2.destroyAllWindows()OpenCV provides built-in functions for selecting regions of interest interactively.
# Select single ROI
cv2.selectROI(windowName, img, showCrosshair=True, fromCenter=False) -> tupleAllows the user to select a region of interest in the image.
Parameters:
windowName (str): Name of the window where selection is performedimg (np.ndarray): Image to select ROI fromshowCrosshair (bool): If True, show crosshair in the center of selectionfromCenter (bool): If True, selection starts from centerReturns:
(x, y, w, h) representing the selected rectangle, or (0, 0, 0, 0) if cancelledControls:
Example:
import cv2
img = cv2.imread('image.jpg')
roi = cv2.selectROI('Select ROI', img, showCrosshair=True)
x, y, w, h = roi
if w > 0 and h > 0:
# Crop selected region
cropped = img[y:y+h, x:x+w]
cv2.imshow('Cropped', cropped)
cv2.waitKey(0)
cv2.destroyAllWindows()# Select multiple ROIs
cv2.selectROIs(windowName, img, showCrosshair=True, fromCenter=False) -> tupleAllows the user to select multiple regions of interest in the image.
Parameters:
windowName (str): Name of the window where selection is performedimg (np.ndarray): Image to select ROIs fromshowCrosshair (bool): If True, show crosshair in the center of selectionfromCenter (bool): If True, selection starts from centerReturns:
(x, y, w, h)Controls:
Example:
import cv2
img = cv2.imread('image.jpg')
rois = cv2.selectROIs('Select Multiple ROIs', img, showCrosshair=True)
# Process each selected ROI
for i, roi in enumerate(rois):
x, y, w, h = roi
if w > 0 and h > 0:
cropped = img[y:y+h, x:x+w]
cv2.imshow(f'ROI {i+1}', cropped)
cv2.waitKey(0)
cv2.destroyAllWindows()OpenCV provides comprehensive drawing functions for visualizing results and creating graphics.
# Draw line
cv2.line(img, pt1, pt2, color, thickness=1, lineType=cv2.LINE_8, shift=0) -> imgDraws a line segment connecting two points.
Parameters:
img (np.ndarray): Image to draw on (modified in-place)pt1 (tuple): First point (x, y)pt2 (tuple): Second point (x, y)color (tuple): Line color (B, G, R) for color images or intensity for grayscalethickness (int): Line thickness in pixelslineType (int): Line type (see Line Types)shift (int): Number of fractional bits in point coordinatesReturns:
Example:
import cv2
import numpy as np
img = np.zeros((512, 512, 3), np.uint8)
# Draw red line from (0,0) to (511,511)
cv2.line(img, (0, 0), (511, 511), (0, 0, 255), 5)# Draw arrowed line
cv2.arrowedLine(img, pt1, pt2, color, thickness=1, lineType=cv2.LINE_8, shift=0, tipLength=0.1) -> imgDraws an arrow segment pointing from the first point to the second.
Parameters:
img (np.ndarray): Image to draw onpt1 (tuple): Starting point (x, y)pt2 (tuple): End point (x, y) - arrow points herecolor (tuple): Line colorthickness (int): Line thicknesslineType (int): Line typeshift (int): Number of fractional bitstipLength (float): Length of arrow tip relative to arrow lengthExample:
cv2.arrowedLine(img, (50, 50), (200, 200), (255, 0, 0), 3, tipLength=0.3)# Draw rectangle
cv2.rectangle(img, pt1, pt2, color, thickness=1, lineType=cv2.LINE_8, shift=0) -> imgDraws a rectangle.
Parameters:
img (np.ndarray): Image to draw onpt1 (tuple): Top-left corner (x, y)pt2 (tuple): Bottom-right corner (x, y)color (tuple): Rectangle colorthickness (int): Line thickness. Use -1 for filled rectanglelineType (int): Line typeshift (int): Number of fractional bitsAlternative signature:
cv2.rectangle(img, rec, color, thickness=1, lineType=cv2.LINE_8, shift=0) -> imgWhere rec is a tuple (x, y, w, h).
Example:
# Outline rectangle
cv2.rectangle(img, (50, 50), (200, 200), (0, 255, 0), 3)
# Filled rectangle
cv2.rectangle(img, (250, 50), (400, 200), (255, 0, 0), -1)# Draw circle
cv2.circle(img, center, radius, color, thickness=1, lineType=cv2.LINE_8, shift=0) -> imgDraws a circle.
Parameters:
img (np.ndarray): Image to draw oncenter (tuple): Center of the circle (x, y)radius (int): Radius of the circlecolor (tuple): Circle colorthickness (int): Circle outline thickness. Use -1 for filled circlelineType (int): Line typeshift (int): Number of fractional bitsExample:
# Outline circle
cv2.circle(img, (256, 256), 50, (0, 255, 255), 2)
# Filled circle
cv2.circle(img, (400, 400), 30, (255, 255, 0), -1)# Draw ellipse
cv2.ellipse(img, center, axes, angle, startAngle, endAngle, color, thickness=1, lineType=cv2.LINE_8, shift=0) -> imgDraws an ellipse or elliptic arc.
Parameters:
img (np.ndarray): Image to draw oncenter (tuple): Center of the ellipse (x, y)axes (tuple): Half of the size of the ellipse main axes (width, height)angle (float): Ellipse rotation angle in degreesstartAngle (float): Starting angle of the elliptic arc in degreesendAngle (float): Ending angle of the elliptic arc in degreescolor (tuple): Ellipse colorthickness (int): Line thickness. Use -1 for filled ellipselineType (int): Line typeshift (int): Number of fractional bitsAlternative signature using RotatedRect:
cv2.ellipse(img, box, color, thickness=1, lineType=cv2.LINE_8) -> imgExample:
# Full ellipse
cv2.ellipse(img, (256, 256), (100, 50), 0, 0, 360, (255, 0, 255), 2)
# Elliptic arc (quarter circle)
cv2.ellipse(img, (256, 256), (100, 50), 45, 0, 90, (0, 255, 0), 3)
# Filled ellipse
cv2.ellipse(img, (400, 100), (80, 40), 30, 0, 360, (128, 128, 255), -1)# Draw polylines
cv2.polylines(img, pts, isClosed, color, thickness=1, lineType=cv2.LINE_8, shift=0) -> imgDraws one or more polygonal curves.
Parameters:
img (np.ndarray): Image to draw onpts (list): Array of polygonal curves. Each curve is represented by an array of pointsisClosed (bool): If True, draw closed polylines (connect last point to first)color (tuple): Polyline colorthickness (int): Line thicknesslineType (int): Line typeshift (int): Number of fractional bitsExample:
import numpy as np
# Triangle
pts = np.array([[100, 50], [50, 150], [150, 150]], np.int32)
pts = pts.reshape((-1, 1, 2))
cv2.polylines(img, [pts], True, (0, 255, 0), 3)
# Multiple polylines
pts1 = np.array([[200, 200], [250, 250], [300, 200]], np.int32).reshape((-1, 1, 2))
pts2 = np.array([[350, 200], [400, 250], [450, 200]], np.int32).reshape((-1, 1, 2))
cv2.polylines(img, [pts1, pts2], False, (255, 255, 0), 2)# Fill polygon
cv2.fillPoly(img, pts, color, lineType=cv2.LINE_8, shift=0, offset=(0, 0)) -> imgFills the area bounded by one or more polygons.
Parameters:
img (np.ndarray): Image to draw onpts (list): Array of polygons. Each polygon is represented by an array of pointscolor (tuple): Polygon fill colorlineType (int): Line typeshift (int): Number of fractional bitsoffset (tuple): Optional offset for all pointsExample:
import numpy as np
# Filled triangle
pts = np.array([[100, 50], [50, 150], [150, 150]], np.int32)
pts = pts.reshape((-1, 1, 2))
cv2.fillPoly(img, [pts], (0, 255, 0))
# Multiple filled polygons
pts1 = np.array([[200, 200], [250, 250], [300, 200]], np.int32).reshape((-1, 1, 2))
pts2 = np.array([[350, 200], [400, 250], [450, 200], [425, 150]], np.int32).reshape((-1, 1, 2))
cv2.fillPoly(img, [pts1, pts2], (255, 0, 255))# Fill convex polygon (faster alternative for convex polygons)
cv2.fillConvexPoly(img, points, color, lineType=cv2.LINE_8, shift=0) -> imgFills a convex polygon. This function is faster than fillPoly but only works with convex polygons.
Parameters:
img (np.ndarray): Image to draw onpoints (np.ndarray): Array of polygon verticescolor (tuple): Polygon fill colorlineType (int): Line typeshift (int): Number of fractional bits# Draw text
cv2.putText(img, text, org, fontFace, fontScale, color, thickness=1, lineType=cv2.LINE_8, bottomLeftOrigin=False) -> imgDraws a text string on the image.
Parameters:
img (np.ndarray): Image to draw ontext (str): Text string to draworg (tuple): Bottom-left corner of the text string in the image (x, y)fontFace (int): Font type (see Font Types)fontScale (float): Font scale factor (multiplied by font-specific base size)color (tuple): Text colorthickness (int): Thickness of the lines used to draw textlineType (int): Line typebottomLeftOrigin (bool): If True, image data origin is at bottom-left cornerExample:
# Simple text
cv2.putText(img, 'OpenCV', (50, 50), cv2.FONT_HERSHEY_SIMPLEX,
1, (255, 255, 255), 2)
# Larger, thicker text
cv2.putText(img, 'Hello World!', (100, 150), cv2.FONT_HERSHEY_DUPLEX,
2, (0, 255, 0), 3)
# Italic text
cv2.putText(img, 'Italic', (50, 250),
cv2.FONT_HERSHEY_SIMPLEX | cv2.FONT_ITALIC,
1.5, (255, 0, 255), 2)# Get text size
cv2.getTextSize(text, fontFace, fontScale, thickness) -> (text_size, baseline)Calculates the width and height of a text string. Useful for positioning text.
Parameters:
text (str): Text stringfontFace (int): Font typefontScale (float): Font scale factorthickness (int): Text thicknessReturns:
text_size (tuple): Size of text box (width, height)baseline (int): y-coordinate of baseline relative to bottom-most text pointExample:
text = 'OpenCV'
font = cv2.FONT_HERSHEY_SIMPLEX
scale = 1
thickness = 2
(text_width, text_height), baseline = cv2.getTextSize(text, font, scale, thickness)
# Center text in image
x = (img.shape[1] - text_width) // 2
y = (img.shape[0] + text_height) // 2
cv2.putText(img, text, (x, y), font, scale, (255, 255, 255), thickness)# Draw marker
cv2.drawMarker(img, position, color, markerType=cv2.MARKER_CROSS, markerSize=20, thickness=1, lineType=cv2.LINE_8) -> imgDraws a marker at the specified position.
Parameters:
img (np.ndarray): Image to draw onposition (tuple): Marker position (x, y)color (tuple): Marker colormarkerType (int): Marker type (see Marker Types)markerSize (int): Marker sizethickness (int): Line thicknesslineType (int): Line typeExample:
# Different marker types
cv2.drawMarker(img, (100, 100), (255, 0, 0), cv2.MARKER_CROSS, 20, 2)
cv2.drawMarker(img, (200, 100), (0, 255, 0), cv2.MARKER_TILTED_CROSS, 20, 2)
cv2.drawMarker(img, (300, 100), (0, 0, 255), cv2.MARKER_STAR, 20, 2)
cv2.drawMarker(img, (400, 100), (255, 255, 0), cv2.MARKER_DIAMOND, 20, 2)Constants for marker shapes:
cv2.MARKER_CROSS # Cross marker (+)
cv2.MARKER_TILTED_CROSS # Tilted cross marker (x)
cv2.MARKER_STAR # Star marker (*)
cv2.MARKER_DIAMOND # Diamond marker (◇)
cv2.MARKER_SQUARE # Square marker (□)
cv2.MARKER_TRIANGLE_UP # Upward triangle marker (△)
cv2.MARKER_TRIANGLE_DOWN # Downward triangle marker (▽)Constants for line rendering:
cv2.LINE_4 # 4-connected line
cv2.LINE_8 # 8-connected line (default)
cv2.LINE_AA # Anti-aliased line (smooth)Note: LINE_AA produces smooth, anti-aliased lines but is computationally more expensive.
Constants for text rendering:
cv2.FONT_HERSHEY_SIMPLEX # Normal sans-serif font
cv2.FONT_HERSHEY_PLAIN # Small sans-serif font
cv2.FONT_HERSHEY_DUPLEX # Normal sans-serif font (more complex than SIMPLEX)
cv2.FONT_HERSHEY_COMPLEX # Normal serif font
cv2.FONT_HERSHEY_TRIPLEX # Normal serif font (more complex than COMPLEX)
cv2.FONT_HERSHEY_COMPLEX_SMALL # Smaller version of COMPLEX
cv2.FONT_HERSHEY_SCRIPT_SIMPLEX # Hand-writing style font
cv2.FONT_HERSHEY_SCRIPT_COMPLEX # More complex hand-writing style font
cv2.FONT_ITALIC # Flag for italic font (combine with OR)Example - Font Comparison:
import cv2
import numpy as np
img = np.zeros((600, 800, 3), np.uint8)
fonts = [
cv2.FONT_HERSHEY_SIMPLEX,
cv2.FONT_HERSHEY_PLAIN,
cv2.FONT_HERSHEY_DUPLEX,
cv2.FONT_HERSHEY_COMPLEX,
cv2.FONT_HERSHEY_TRIPLEX,
cv2.FONT_HERSHEY_SCRIPT_SIMPLEX,
cv2.FONT_HERSHEY_SCRIPT_COMPLEX
]
font_names = [
'HERSHEY_SIMPLEX',
'HERSHEY_PLAIN',
'HERSHEY_DUPLEX',
'HERSHEY_COMPLEX',
'HERSHEY_TRIPLEX',
'SCRIPT_SIMPLEX',
'SCRIPT_COMPLEX'
]
for i, (font, name) in enumerate(zip(fonts, font_names)):
y = 50 + i * 70
cv2.putText(img, name, (50, y), font, 1, (255, 255, 255), 2)
cv2.imshow('Font Comparison', img)
cv2.waitKey(0)
cv2.destroyAllWindows()Complete Drawing Example:
import cv2
import numpy as np
# Create blank image
img = np.zeros((512, 512, 3), np.uint8)
# Draw various shapes
cv2.line(img, (0, 0), (511, 511), (255, 0, 0), 5)
cv2.rectangle(img, (384, 0), (510, 128), (0, 255, 0), 3)
cv2.circle(img, (447, 63), 63, (0, 0, 255), -1)
cv2.ellipse(img, (256, 256), (100, 50), 0, 0, 180, (255, 255, 0), -1)
# Draw polygon
pts = np.array([[10, 5], [20, 30], [70, 20], [50, 10]], np.int32)
pts = pts.reshape((-1, 1, 2))
cv2.polylines(img, [pts], True, (0, 255, 255), 3)
# Draw text
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img, 'OpenCV Drawing', (10, 450), font, 1, (255, 255, 255), 2, cv2.LINE_AA)
# Draw markers
cv2.drawMarker(img, (100, 100), (255, 0, 255), cv2.MARKER_CROSS, 20, 2)
cv2.drawMarker(img, (150, 100), (255, 0, 255), cv2.MARKER_STAR, 20, 2)
# Display
cv2.imshow('Drawing Demo', img)
cv2.waitKey(0)
cv2.destroyAllWindows()cv2.waitKey() after cv2.imshow() to allow the window to rendercv2.destroyAllWindows() at the end of your program to clean upcv2.WINDOW_NORMAL flag if you need to resize themcv2.selectROI() for user-friendly region selectionimg.copy() if you need to preserve the original imageLINE_AA) are slower than standard lines(intensity,) or just intensitycv2.getTextSize() to calculate text dimensions for proper positioningcv2.FONT_ITALIC using bitwise OR: cv2.FONT_HERSHEY_SIMPLEX | cv2.FONT_ITALICcv2.imshow() liberally during development for debuggingInstall with Tessl CLI
npx tessl i tessl/pypi-opencv-python