1. Home
  2. Explore
  3. Computer Science
  4. Python OpenCV Computer Vision

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Python OpenCV Computer Vision

Python and OpenCV Study Notes

1. Computer Vision and OpenCV

Computer vision is a field of computing concerned with extracting useful information from images and videos. It is commonly associated with deep learning, although many computer-vision tasks can also be performed using traditional image-processing algorithms.

OpenCV is a computer-vision library available for:

  • Python

  • C++

  • Java

OpenCV provides tools for:

  • Reading and displaying images and videos

  • Resizing and transforming media

  • Drawing shapes and text

  • Converting between color spaces

  • Applying masks and bitwise operations

  • Computing histograms

  • Detecting edges and contours

  • Thresholding images

  • Detecting and recognizing faces

  • Supporting deep-learning workflows

A typical computer-vision workflow may involve:

  1. Reading an image or video.

  2. Converting it into a suitable color space.

  3. Resizing or normalizing the media.

  4. Removing noise or detecting edges.

  5. Applying masks or extracting regions of interest.

  6. Drawing results or making predictions.


2. Installation and Required Packages

Python Version

The material assumes that Python is already installed. The installed version can be checked from a terminal with:

python --version

A Python version of 3.7 or later is recommended. Some code may not work correctly with older versions, especially Python 2.

OpenCV

The recommended installation is:

pip install opencv-contrib-python

The opencv-python package contains the core OpenCV functionality. The opencv-contrib-python package includes the core functionality plus additional community-contributed modules.

The contribution package is useful because it includes functionality such as:

  • Additional algorithms

  • Face-recognition tools

  • Experimental or extended computer-vision modules

OpenCV is generally imported in Python as:

import cv2 as cv

NumPy

NumPy is a scientific-computing library used extensively with OpenCV. OpenCV images are represented as NumPy arrays, so NumPy is important for:

  • Matrix manipulation

  • Array slicing

  • Reshaping

  • Creating blank images

  • Pixel-level operations

  • Numerical transformations

It is commonly imported as:

import numpy as np

NumPy arrays representing images usually contain pixel values in the range 000 to 255255255 when using the unsigned 8-bit image data type.

Utility Packages

The source also introduces utility packages designed to simplify computer-vision and deep-learning workflows:

  • A computer-vision utility package containing helper functions for preprocessing and image handling.

  • A Keras-oriented deep-learning utility package for creating and training models.

These packages are not essential for understanding the basic OpenCV operations, but they can reduce repetitive code in larger projects.


3. Reading Images and Videos

Reading Images

OpenCV reads an image with cv.imread():

img = cv.imread("photos/cat.jpg")

The method:

  • Receives a path to an image.

  • Loads the image from that location.

  • Returns the image as a matrix of pixel values.

Both relative and absolute paths can be used.

Relative Paths

A relative path is interpreted from the current working directory:

img = cv.imread("photos/cat.jpg")

This works when the photos folder is located inside the current project directory.

Displaying an Image

The cv.imshow() function displays an image in a new window:

cv.imshow("Cat", img)

It accepts:

  1. A window name.

  2. The image matrix to display.

The displayed window can disappear immediately unless the program is paused. cv.waitKey() is used to wait for keyboard input:

cv.waitKey(0)

The argument is measured in milliseconds:

  • cv.waitKey(0) waits indefinitely.

  • cv.waitKey(20) waits approximately 20 milliseconds.

A typical image-display sequence is:

img = cv.imread("photos/cat.jpg")
cv.imshow("Cat", img)
cv.waitKey(0)

Large Images

OpenCV does not automatically resize images that are larger than the computer screen. A high-resolution image may therefore extend beyond the visible screen.

For example, an image with dimensions 2400×16002400 \times 16002400×1600 may be too large to display comfortably on a smaller monitor. The usual solution is to resize or rescale it before displaying it.


Reading Videos

Videos are read using the cv.VideoCapture class:

capture = cv.VideoCapture("videos/dog.mp4")

VideoCapture can receive either:

  • A path to an existing video file.

  • An integer identifying a camera.

Camera Indices

Camera indices commonly work as follows:

  • 0: default webcam

  • 1: first additional camera

  • 2: second additional camera

For example:

capture = cv.VideoCapture(0)

opens the default webcam.

Reading a Video Frame by Frame

Unlike a still image, a video consists of many frames. Each frame must be read individually inside a loop:

while True:
    is_true, frame = capture.read()
    cv.imshow("Video", frame)

    if cv.waitKey(20) & 0xFF == ord("d"):
        break

capture.release()
cv.destroyAllWindows()

The capture.read() method returns two values:

  • A Boolean indicating whether the frame was successfully read.

  • The actual frame.

The Boolean is useful because it indicates whether another valid frame is available.

Stopping Video Playback

The expression:

cv.waitKey(20) & 0xFF == ord("d")

checks whether the d key has been pressed. If so, the loop is exited.

The & 0xFF operation extracts the relevant part of the keyboard response returned by cv.waitKey().

Releasing Resources

After video processing, two cleanup operations are important:

capture.release()
cv.destroyAllWindows()
  • capture.release() releases the camera or video-file resource.

  • cv.destroyAllWindows() closes all OpenCV windows.

Media-File Errors

OpenCV may raise an assertion failure, often associated with an error such as (-215), when it cannot read a media file. Common causes include:

  • The file path is incorrect.

  • The file does not exist.

  • The file format is unsupported.

  • A video has reached its final frame.

  • The program attempts to read a frame after the video has ended.

A video may unexpectedly leave the loop or generate an error when no more frames are available. Checking the Boolean returned by capture.read() can help handle this situation safely.


4. Resizing and Rescaling Images and Video

Large images and videos require more memory and processing power. Rescaling reduces their width and height, lowering computational cost and making display and processing more efficient.

Downscaling is generally preferred because a camera cannot usually produce more detail than its hardware supports. For example, a camera designed to capture at 720720720 pixels cannot create genuine 108010801080-pixel detail simply by requesting a larger output size.

A General Rescaling Function

A reusable rescaling function can calculate new dimensions from a scale factor:

def rescale_frame(frame, scale=0.75):
    width = int(frame.shape[1] * scale)
    height = int(frame.shape[0] * scale)
    dimensions = (width, height)

    return cv.resize(
        frame,
        dimensions,
        interpolation=cv.INTER_AREA
    )

Image Array Dimensions

For an image array:

  • frame.shape[0] represents height.

  • frame.shape[1] represents width.

  • frame.shape[2] represents the number of color channels.

Thus, a color image may have a shape such as:

(height, width, 3)

The scale factor multiplies both width and height. A scale of 0.750.750.75 produces dimensions that are 75%75\%75% of the original values.

Interpolation

Interpolation determines how OpenCV estimates pixel values while resizing.

  • cv.INTER_AREA: generally effective when shrinking an image.

  • cv.INTER_LINEAR: useful for general resizing and enlargement.

  • cv.INTER_CUBIC: slower but often produces higher-quality enlargement.

Rescaling Images and Video Frames

The same rescaling function can be used for:

  • Still images

  • Existing video files

  • Individual video frames

  • Live camera frames

Example:

resized = rescale_frame(img, scale=0.2)
cv.imshow("Resized", resized)

For video, each frame can be rescaled before it is displayed.

Changing Live-Video Resolution

OpenCV also provides capture.set() for changing properties of a live capture device:

capture.set(3, width)
capture.set(4, height)

The property identifiers commonly used are:

  • 3: frame width

  • 4: frame height

This approach is intended for live video from a webcam or external camera. It does not reliably resize an existing video file. For an existing image or video file, cv.resize() is the appropriate operation.


5. Drawing on Images

OpenCV can draw on an existing image or on a blank image created with NumPy.

Creating a Blank Image

A blank image can be created using:

blank = np.zeros((500, 500, 3), dtype="uint8")

The three dimensions represent:

  1. Height

  2. Width

  3. Number of color channels

The data type uint8 is standard for ordinary images because each channel uses values from 000 to 255255255.

A grayscale blank image would have only two dimensions:

blank = np.zeros((500, 500), dtype="uint8")

A color image requires three channels.

Color Ordering in OpenCV

OpenCV uses BGR ordering, not the more commonly discussed RGB ordering:

Blue, Green, Red

Examples:

  • Blue: (255,0,0)(255, 0, 0)(255,0,0)

  • Green: (0,255,0)(0, 255, 0)(0,255,0)

  • Red: (0,0,255)(0, 0, 255)(0,0,255)

  • White: (255,255,255)(255, 255, 255)(255,255,255)

  • Black: (0,0,0)(0, 0, 0)(0,0,0)

Filling an Image or Region

All pixels can be assigned a color:

blank[:] = 0, 255, 0

This produces a green image in BGR format.

A rectangular region can be changed with array slicing:

blank[200:300, 300:400] = 0, 0, 255

This colors a region red.

The general slicing form is:

image[y_start:y_end, x_start:x_end]

Rows correspond to the vertical coordinate yyy, and columns correspond to the horizontal coordinate xxx.


Drawing Rectangles

Rectangles are drawn with:

cv.rectangle(image, point1, point2, color, thickness)

Example:

cv.rectangle(
    blank,
    (0, 0),
    (250, 250),
    (0, 255, 0),
    thickness=2
)

The arguments represent:

  • Image to modify

  • Top-left corner

  • Bottom-right corner

  • BGR color

  • Border thickness

A rectangle can be filled by using:

thickness=-1

or:

thickness=cv.FILLED

The rectangle dimensions can also be calculated relative to the image:

cv.rectangle(
    blank,
    (0, 0),
    (blank.shape[1] // 2, blank.shape[0] // 2),
    (0, 255, 0),
    thickness=2
)

Drawing Circles

Circles are drawn with:

cv.circle(image, center, radius, color, thickness)

Example:

cv.circle(
    blank,
    (250, 250),
    40,
    (0, 0, 255),
    thickness=3
)

The arguments specify:

  • Image to modify

  • Center coordinate

  • Radius in pixels

  • BGR color

  • Border thickness

A filled circle is created with thickness=-1.


Drawing Lines

Lines are drawn with:

cv.line(image, point1, point2, color, thickness)

Example:

cv.line(
    blank,
    (100, 100),
    (300, 400),
    (255, 255, 255),
    thickness=3
)

The line connects the two specified coordinates.


Writing Text

Text is added with:

cv.putText(
    image,
    text,
    origin,
    font,
    font_scale,
    color,
    thickness
)

Example:

cv.putText(
    blank,
    "Hello",
    (225, 225),
    cv.FONT_HERSHEY_TRIPLEX,
    1.0,
    (0, 255, 0),
    2
)

The origin indicates where the text begins. OpenCV includes several built-in Hershey fonts, including:

  • FONT_HERSHEY_SIMPLEX

  • FONT_HERSHEY_PLAIN

  • FONT_HERSHEY_DUPLEX

  • FONT_HERSHEY_COMPLEX

  • FONT_HERSHEY_TRIPLEX

  • Script-style variants

Text can extend beyond the image if the origin and font size are not selected carefully.


6. Basic Image-Processing Functions

Converting BGR to Grayscale

A standard OpenCV image has three BGR channels. A grayscale image contains only intensity information.

Grayscale conversion is performed with:

gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)

A grayscale image represents brightness rather than color:

  • Dark pixels have low intensity.

  • Bright pixels have high intensity.

  • Color differences are removed.

Grayscale images are useful because many algorithms, including edge detection and face detection, do not require color information.


Gaussian Blurring

Blurring reduces image noise. Noise may result from:

  • Poor lighting

  • Camera-sensor limitations

  • Unwanted fine details

  • Compression artifacts

Gaussian blur is applied with:

blur = cv.GaussianBlur(
    img,
    (3, 3),
    cv.BORDER_DEFAULT
)

The kernel size determines the neighborhood used to calculate the new pixel values. A larger kernel produces stronger blurring:

blur = cv.GaussianBlur(
    img,
    (7, 7),
    cv.BORDER_DEFAULT
)

Kernel dimensions generally need to be odd values, such as:

  • 3×33 \times 33×3

  • 5×55 \times 55×5

  • 7×77 \times 77×7

Blurring is often performed before edge detection because it removes small variations that might otherwise be interpreted as edges.


Canny Edge Detection

The Canny edge detector identifies strong changes in intensity:

canny = cv.Canny(img, 125, 175)

The two threshold values control which intensity changes are considered edges.

Canny detection is a multistep process involving operations such as:

  1. Noise reduction.

  2. Gradient computation.

  3. Identification of likely edges.

  4. Edge thinning.

  5. Edge tracking using threshold relationships.

Applying Canny to a blurred image usually produces fewer and cleaner edges:

canny = cv.Canny(blur, 125, 175)

This is useful when the original image contains many small details or noise.


Dilating an Image

Dilation expands bright regions and thickens detected structures. It can be applied to edge images:

dilated = cv.dilate(
    canny,
    (3, 3),
    iterations=1
)

Important parameters include:

  • The source image.

  • The kernel size.

  • The number of iterations.

Increasing the kernel size or number of iterations generally makes the edges thicker.


Eroding an Image

Erosion reduces or thins bright regions. It can be applied after dilation:

eroded = cv.erode(
    dilated,
    (3, 3),
    iterations=1
)

Erosion may partially restore an image to its earlier appearance, although it does not always perfectly reverse dilation. Matching the kernel and iteration parameters can produce a result visually similar to the original edge image.


Resizing an Image

The direct resizing operation is:

resized = cv.resize(
    img,
    (500, 500),
    interpolation=cv.INTER_AREA
)

This forces the image to the specified destination dimensions. If the requested dimensions do not preserve the original aspect ratio, the image may appear stretched or compressed.


Cropping with Array Slicing

Images are NumPy arrays, so cropping can be performed through slicing:

cropped = img[50:200, 200:400]

This selects:

  • Rows from 505050 through 199199199.

  • Columns from 200200200 through 399399399.

Cropping is useful for selecting a region of interest, such as a face or object.


7. Basic Image Transformations

Translation

Translation shifts an image along the horizontal and vertical axes without changing its orientation.

A translation matrix has the form:

M=[10x01y]M = \begin{bmatrix} 1 & 0 & x \\ 0 & 1 & y \end{bmatrix}M=[10​01​xy​]

where:

  • xxx is the horizontal shift.

  • yyy is the vertical shift.

A translation function can be implemented as:

def translate(image, x, y):
    trans_matrix = np.float32([
        [1, 0, x],
        [0, 1, y]
    ])

    dimensions = (image.shape[1], image.shape[0])

    return cv.warpAffine(
        image,
        trans_matrix,
        dimensions
    )

Direction rules:

  • Positive xxx: shift right.

  • Negative xxx: shift left.

  • Positive yyy: shift down.

  • Negative yyy: shift up.

Example:

translated = translate(img, 100, 100)

moves the image right and down by 100100100 pixels.


Rotation

Rotation changes an image’s orientation around a chosen point. By default, rotation is usually performed around the image center.

The rotation matrix is generated with:

rot_matrix = cv.getRotationMatrix2D(
    rotation_point,
    angle,
    scale
)

A reusable function is:

def rotate(image, angle, rotation_point=None):
    height, width = image.shape[:2]

    if rotation_point is None:
        rotation_point = (width // 2, height // 2)

    rot_matrix = cv.getRotationMatrix2D(
        rotation_point,
        angle,
        1.0
    )

    dimensions = (width, height)

    return cv.warpAffine(
        image,
        rot_matrix,
        dimensions
    )

Direction rules:

  • Positive angles rotate counterclockwise.

  • Negative angles rotate clockwise.

Rotation can introduce black triangular regions because the rotated image no longer fills the original rectangular frame. These areas are empty and are filled with black by default.

If multiple rotations are required, it is usually better to add the angles together and perform one rotation rather than repeatedly rotating the already-rotated image. Repeated transformations may compound interpolation artifacts and rotate empty regions as well.


Resizing

Resizing changes an image’s dimensions:

resized = cv.resize(
    img,
    (500, 500),
    interpolation=cv.INTER_AREA
)

The choice of interpolation depends on whether the image is being enlarged or reduced.


Flipping

Images are flipped with:

flipped = cv.flip(img, flipCode)

The flip code specifies the direction:

  • 0: flip vertically, across the horizontal axis.

  • 1: flip horizontally, across the vertical axis.

  • -1: flip both vertically and horizontally.

Examples:

vertical = cv.flip(img, 0)
horizontal = cv.flip(img, 1)
both = cv.flip(img, -1)

Cropping

Cropping uses NumPy slicing:

cropped = img[200:400, 100:300]

The crop is specified as a range of rows followed by a range of columns.


8. Contours

A contour is a curve joining continuous points along the boundary of an object. Contours are useful for:

  • Shape analysis

  • Object detection

  • Object recognition

  • Measuring object boundaries

  • Finding geometric structures

Contours and edges are related but are not mathematically identical. An edge is a local intensity change, while a contour represents a boundary curve formed from connected points. In practical OpenCV programming, contours are often treated as object boundaries derived from edge information.

Preparing an Image for Contour Detection

A common pipeline is:

  1. Convert the image to grayscale.

  2. Blur the grayscale image.

  3. Detect edges with Canny.

  4. Find contours from the resulting edge image.

Example:

gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
blur = cv.GaussianBlur(gray, (5, 5), cv.BORDER_DEFAULT)
canny = cv.Canny(blur, 125, 175)

Finding Contours

Contours are found with:

contours, hierarchies = cv.findContours(
    canny,
    cv.RETR_LIST,
    cv.CHAIN_APPROX_SIMPLE
)

The function returns:

  • contours: a list containing the detected contours.

  • hierarchies: relationships among contours.

Contour Retrieval Modes

  • cv.RETR_LIST: retrieves all contours without establishing a strict parent-child hierarchy.

  • cv.RETR_EXTERNAL: retrieves only the outermost contours.

  • cv.RETR_TREE: retrieves contours and their complete hierarchical relationships.

A hierarchy is relevant when contours are nested, such as:

  • A rectangle containing a square.

  • A square containing a circle.

  • An object containing holes or internal boundaries.

Contour Approximation Methods

  • cv.CHAIN_APPROX_NONE: stores all boundary points.

  • cv.CHAIN_APPROX_SIMPLE: compresses redundant points and stores only the points necessary to represent the contour.

For example, a straight line contains many points, but CHAIN_APPROX_SIMPLE may preserve only its two endpoints.

Effect of Blurring on Contours

Images with noise or many small details may produce thousands of contours. Blurring before edge detection reduces small variations and can significantly reduce the number of detected contours.

A larger blur kernel often produces fewer, smoother contours, although excessive blur may remove important object boundaries.

Drawing Contours

Contours can be visualized on a blank image:

blank = np.zeros(img.shape[:2], dtype="uint8")

cv.drawContours(
    blank,
    contours,
    -1,
    (0, 0, 255),
    1
)

The contour index -1 means that all detected contours should be drawn.


9. Color Spaces

A color space is a system for representing colors. OpenCV supports several color spaces, including:

  • BGR

  • RGB

  • Grayscale

  • HSV

  • LAB

BGR

OpenCV reads ordinary color images in BGR order:

Blue, Green, Red

This differs from the RGB convention used by many other libraries.

Grayscale

A grayscale image contains one intensity channel rather than three color channels:

gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)

Grayscale is useful when color is unnecessary, such as for:

  • Edge detection

  • Thresholding

  • Face detection

  • Shape analysis

HSV

HSV stands for:

  • Hue

  • Saturation

  • Value

HSV is often considered more intuitive for describing colors because it separates:

  • The type of color, represented by hue.

  • The intensity or purity of the color, represented by saturation.

  • The brightness, represented by value.

Conversion:

hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV)

HSV is useful in tasks such as color-based object detection.

LAB

LAB is another color space designed to represent color in a way that is more closely related to human perception.

Conversion:

lab = cv.cvtColor(img, cv.COLOR_BGR2LAB)

It is sometimes written as Lab*, with components representing lightness and color dimensions.

RGB and Matplotlib

Matplotlib generally expects images in RGB order, while OpenCV uses BGR. Displaying a BGR image directly with Matplotlib results in inverted colors.

Conversion:

rgb = cv.cvtColor(img, cv.COLOR_BGR2RGB)

The general rule is:

  • Use BGR when working directly with OpenCV.

  • Convert BGR to RGB before displaying an OpenCV image with Matplotlib.

Similarly, if an RGB image is supplied to OpenCV as though it were BGR, its colors will appear reversed.

Reverse Conversions

OpenCV can convert many color spaces back to BGR:

bgr_from_hsv = cv.cvtColor(hsv, cv.COLOR_HSV2BGR)
bgr_from_lab = cv.cvtColor(lab, cv.COLOR_LAB2BGR)

A grayscale image cannot generally be converted directly to HSV in one meaningful step because HSV requires color information. A grayscale image can first be converted to BGR and then converted to HSV if necessary.


10. Splitting and Merging Color Channels

A color image is composed of separate channels. In OpenCV, a BGR image has:

  1. Blue channel

  2. Green channel

  3. Red channel

Splitting Channels

b, g, r = cv.split(img)

Each returned channel is a single-channel image. When displayed, it appears grayscale because it represents the intensity distribution of one color.

Interpreting Channel Images

  • Bright areas in the blue-channel image contain high blue intensity.

  • Bright areas in the green-channel image contain high green intensity.

  • Bright areas in the red-channel image contain high red intensity.

  • Dark areas contain little of that channel’s color.

The original color image may have shape:

(height, width, 3)

Each individual channel has shape:

(height, width)

The absent third dimension means that each channel contains one value per pixel.

Merging Channels

The original image can be reconstructed with:

merged = cv.merge([b, g, r])

The channel order must be correct. Reordering the channels changes the resulting colors.

Visualizing a Channel in Its Actual Color

A channel can be placed into one color position while the other channels are set to zero.

For example, to display only the blue contribution:

blank = np.zeros(img.shape[:2], dtype="uint8")
blue = cv.merge([b, blank, blank])

For the green contribution:

green = cv.merge([blank, g, blank])

For the red contribution:

red = cv.merge([blank, blank, r])

The intensity of each channel controls how bright that color appears.


11. Smoothing and Blurring Techniques

Blurring replaces a pixel’s value using information from neighboring pixels. A kernel, or window, defines the neighborhood used for this calculation.

For a 3×33 \times 33×3 kernel, the center pixel is recalculated using the surrounding pixels in the window. As the kernel moves across the image, this operation is repeated for many pixels.

Larger kernels consider larger neighborhoods and generally produce stronger smoothing.

Averaging Blur

Averaging replaces the center pixel with the average of surrounding pixel intensities.

For surrounding values p1,p2,…,pnp_1, p_2, \ldots, p_np1​,p2​,…,pn​, the new value can be represented as:

new intensity=1n∑i=1npi\text{new intensity} = \frac{1}{n} \sum_{i=1}^{n} p_inew intensity=n1​∑i=1n​pi​

OpenCV applies averaging with:

average = cv.blur(img, (3, 3))

A larger kernel, such as (7,7)(7, 7)(7,7), creates more blur.

Gaussian Blur

Gaussian blur also uses a neighborhood, but it assigns different weights to the pixels. Pixels closer to the center generally have greater influence.

gaussian = cv.GaussianBlur(
    img,
    (7, 7),
    0
)

Compared with simple averaging:

  • Gaussian blur often appears more natural.

  • It usually produces less harsh smoothing.

  • It is widely used before edge detection.

Median Blur

Median blur replaces the center pixel with the median value of the surrounding neighborhood:

median = cv.medianBlur(img, 3)

Unlike Gaussian and averaging blur, the kernel size is supplied as a single integer. OpenCV interprets 3 as a 3×33 \times 33×3 kernel.

Median blurring is particularly useful for:

  • Removing salt-and-pepper noise.

  • Reducing isolated bright or dark pixels.

  • Preserving some edges while removing noise.

Bilateral Filtering

Bilateral filtering smooths an image while preserving edges:

bilateral = cv.bilateralFilter(
    img,
    5,
    15,
    15
)

The parameters include:

  • Diameter of the pixel neighborhood.

  • Color-space standard deviation.

  • Spatial standard deviation.

A larger color sigma allows pixels with more different colors to influence one another. A larger spatial sigma allows pixels farther from the center to affect the result.

Traditional blurring may smooth across object boundaries. Bilateral filtering attempts to avoid this, producing a smoothed image in which important edges remain visible.


12. Bitwise Operators

Bitwise operations work on binary representations. In image processing, pixels are often treated as:

  • Off when their value is 000.

  • On when their value is nonzero, often 255255255.

The four principal operations are:

  • AND

  • OR

  • XOR

  • NOT

These operations are especially useful when constructing masks.

Creating Binary Shapes

A blank single-channel image can be used to create binary shapes:

blank = np.zeros((400, 400), dtype="uint8")

A filled rectangle and circle can then be drawn with pixel value 255255255.

Bitwise AND

bitwise_and = cv.bitwise_and(rectangle, circle)

AND retains only regions that are active in both source images. In geometric terms, it returns their intersection.

A pixel is active in the output only when the corresponding pixel is active in both inputs.

Bitwise OR

bitwise_or = cv.bitwise_or(rectangle, circle)

OR retains regions active in either image. It combines:

  • The intersection.

  • The non-overlapping regions.

Bitwise XOR

bitwise_xor = cv.bitwise_xor(rectangle, circle)

XOR retains regions active in exactly one input but not both. It therefore returns the non-intersecting portions.

Bitwise NOT

bitwise_not = cv.bitwise_not(rectangle)

NOT inverts the binary values:

  • White becomes black.

  • Black becomes white.

These operations allow geometric regions to be combined and manipulated without manually processing every pixel.


13. Masking

A mask selects the portion of an image that should be processed or displayed. Masking is useful when the task concerns only a region of interest, such as:

  • A person’s face

  • A specific object

  • A circular area

  • A rectangular section

  • A color-defined region

Creating a Mask

A mask is generally a single-channel binary image with the same height and width as the source image:

mask = np.zeros(img.shape[:2], dtype="uint8")

A white shape can then be drawn on the mask:

cv.circle(
    mask,
    (img.shape[1] // 2, img.shape[0] // 2),
    100,
    255,
    -1
)

The white region represents the selected area. The black region represents the excluded area.

Applying the Mask

The mask can be applied using a bitwise AND:

masked = cv.bitwise_and(
    img,
    img,
    mask=mask
)

Only pixels inside the white region of the mask remain visible. Pixels outside the mask become black.

Mask Dimensions

The mask must have the same spatial dimensions as the source image:

  • Same height.

  • Same width.

A mismatch produces an assertion failure. A mask is usually single-channel even when the source image is a three-channel color image.

Combining Masks

Multiple shapes can be combined with bitwise operations to create more complex masks. For example:

  1. Create a circle.

  2. Create a rectangle.

  3. Combine them with AND, OR, or XOR.

  4. Use the resulting shape as the mask.

This makes it possible to isolate irregular or compound regions.


14. Histograms

A histogram shows the distribution of pixel intensities in an image.

For a grayscale image, the horizontal axis represents intensity values, commonly from 000 to 255255255:

  • 000: black

  • 255255255: white

The vertical axis represents the number of pixels having each intensity.

Histograms can reveal:

  • Whether an image is mostly dark or bright.

  • Whether pixel values are concentrated in a narrow range.

  • Whether contrast is limited.

  • How different color channels are distributed.

Grayscale Histograms

First, an image is converted to grayscale:

gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)

The histogram is calculated with:

gray_hist = cv.calcHist(
    [gray],
    [0],
    None,
    [256],
    [0, 256]
)

The arguments specify:

  1. A list of images.

  2. The channel index.

  3. A mask, or None for the whole image.

  4. The number of histogram bins.

  5. The intensity range.

With 256256256 bins over the range 000 to 256256256, each bin typically corresponds to one possible 8-bit intensity.

A grayscale histogram can be plotted with Matplotlib:

plt.plot(gray_hist)
plt.xlim([0, 256])
plt.xlabel("Bins")
plt.ylabel("Number of pixels")
plt.show()

Interpreting Peaks

A high peak near an intensity value means that many pixels have values near that intensity. For example:

  • A peak near 000 indicates many dark pixels.

  • A peak near 255255255 indicates many bright pixels.

  • A narrow range of values may indicate low contrast.

Masked Histograms

A histogram can be computed for only part of an image. The mask must identify the region of interest:

masked_hist = cv.calcHist(
    [gray],
    [0],
    mask,
    [256],
    [0, 256]
)

This allows the intensity distribution of a selected face, object, or geometric region to be analyzed separately from the rest of the image.

Color Histograms

For a BGR image, a separate histogram can be calculated for each channel:

colors = ("b", "g", "r")

for i, color in enumerate(colors):
    hist = cv.calcHist(
        [img],
        [i],
        None,
        [256],
        [0, 256]
    )
    plt.plot(hist, color=color)

The resulting plots describe the distributions of:

  • Blue intensities.

  • Green intensities.

  • Red intensities.

The same mask can be supplied for each channel to calculate channel distributions within a specific region.

A mask for cv.calcHist() must be a binary, single-channel image with dimensions matching the source image. A three-channel masked image is not itself a valid histogram mask.


15. Thresholding

Thresholding converts an image into a binary representation. Each pixel becomes either:

  • 000, usually black.

  • A maximum value, commonly 255255255, usually white.

Thresholding is useful for:

  • Separating foreground from background.

  • Preparing images for contour detection.

  • Simplifying image structure.

  • Creating binary masks.

Simple Thresholding

The basic rule is:

T(p)={255,p>t0,p≤tT(p) = \begin{cases} 255, & p > t \\ 0, & p \leq t \end{cases}T(p)={255,0,​p>tp≤t​

where:

  • ppp is the original pixel intensity.

  • ttt is the selected threshold.

OpenCV implementation:

threshold, thresh = cv.threshold(
    gray,
    150,
    255,
    cv.THRESH_BINARY
)

The function returns:

  • The threshold value used.

  • The thresholded image.

Although the threshold value is returned, it is the same manually supplied value in ordinary simple thresholding.

Effect of the Threshold

  • A lower threshold causes more pixels to become white.

  • A higher threshold causes fewer pixels to become white.

For example, a threshold near 100100100 may classify many regions as white, while a threshold near 225225225 may classify only the brightest pixels as white.

Inverse Thresholding

Inverse thresholding reverses the result:

threshold, inverse = cv.threshold(
    gray,
    150,
    255,
    cv.THRESH_BINARY_INV
)

The rule becomes:

T(p)={0,p>t255,p≤tT(p) = \begin{cases} 0, & p > t \\ 255, & p \leq t \end{cases}T(p)={0,255,​p>tp≤t​

Thus, areas that were white become black, and areas that were black become white.

Adaptive Thresholding

Simple thresholding uses one threshold for the entire image. This can fail when lighting varies across the image.

Adaptive thresholding calculates a threshold for local neighborhoods:

adaptive = cv.adaptiveThreshold(
    gray,
    255,
    cv.ADAPTIVE_THRESH_MEAN_C,
    cv.THRESH_BINARY,
    11,
    3
)

Important parameters include:

  • Maximum output value.

  • Adaptive thresholding method.

  • Threshold type.

  • Block size.

  • Constant CCC.

The block size defines the local neighborhood used to calculate a threshold. It is generally an odd integer, such as 111111.

The constant CCC is subtracted from the calculated local statistic. Changing it fine-tunes the result.

Adaptive Mean Thresholding

The threshold is based on the mean intensity of the local neighborhood.

Adaptive Gaussian Thresholding

The threshold is based on a weighted average, where nearby pixels generally receive greater weight:

adaptive = cv.adaptiveThreshold(
    gray,
    255,
    cv.ADAPTIVE_THRESH_GAUSSIAN_C,
    cv.THRESH_BINARY,
    11,
    3
)

Adaptive thresholding is useful when different parts of an image have different lighting conditions.


16. Gradients and Edge Detection

A gradient measures how rapidly image intensity changes. Gradients often appear in regions corresponding to visual edges, although gradients and edges are mathematically distinct concepts.

Laplacian Method

The Laplacian detects changes in intensity in multiple directions:

lap = cv.Laplacian(
    gray,
    cv.CV_64F
)

The result may contain negative pixel values because intensity changes can have positive or negative slopes. Since ordinary image formats cannot directly represent negative intensities, the absolute values are taken and converted to an image type:

lap = np.uint8(np.absolute(lap))

The resulting image emphasizes gradient regions and can resemble a pencil-sketch representation of the image.

Sobel Method

The Sobel operator calculates gradients separately in the horizontal and vertical directions.

Horizontal or xxx Direction

sobel_x = cv.Sobel(
    gray,
    cv.CV_64F,
    1,
    0
)

Vertical or yyy Direction

sobel_y = cv.Sobel(
    gray,
    cv.CV_64F,
    0,
    1
)

The two direction parameters identify the derivative being calculated:

  • 1, 0: gradient in the xxx direction.

  • 0, 1: gradient in the yyy direction.

The two results can be combined:

combined_sobel = cv.bitwise_or(sobel_x, sobel_y)

Comparing Laplacian, Sobel, and Canny

  • Laplacian: detects gradients in multiple directions and often produces a sketch-like result.

  • Sobel: computes directional gradients and is useful when horizontal or vertical changes matter.

  • Canny: is a more advanced multistep edge detector that generally produces cleaner, thinner edges.

Canny commonly includes gradient calculations as one stage of its process, but it adds additional processing to produce a more refined edge map.


17. Face Detection

Detection Versus Recognition

Face detection determines whether and where a face appears in an image.

Face recognition determines whose face it is.

Detection answers:

“Is there a face, and where is it located?”

Recognition answers:

“Which known person does this face belong to?”

Classifiers

A classifier determines whether an image region is positive or negative for a target object. A face classifier is trained using many examples:

  • Positive examples containing faces.

  • Negative examples without faces.

OpenCV provides pretrained classifiers, so a new model does not need to be trained from scratch for basic detection.

Haar Cascades

A Haar cascade is a pretrained object detector stored in an XML file. OpenCV supplies cascades for objects such as:

  • Frontal faces

  • Eyes

  • Smiles

  • Full bodies

  • Upper bodies

  • Cat faces

  • License plates

The frontal-face classifier is commonly stored in a file such as:

haarcascade_frontalface_default.xml

The classifier is loaded with:

haar_cascade = cv.CascadeClassifier(
    "haar_face.xml"
)

Preparing an Image

Face detection generally uses grayscale images because it focuses on structural patterns and edges rather than skin color:

gray = cv.cvtColor(
    img,
    cv.COLOR_BGR2GRAY
)

Detecting Faces

faces_rect = haar_cascade.detectMultiScale(
    gray,
    scaleFactor=1.1,
    minNeighbors=4
)

The method returns rectangular coordinates for detected faces.

Scale Factor

scaleFactor controls how much the image is reduced between searches at different scales. A value such as 1.11.11.1 searches through nearby scales.

Minimum Neighbors

minNeighbors determines how many nearby candidate rectangles are required before a region is considered a valid detection.

  • Lower values detect more possible faces but are more sensitive to noise.

  • Higher values reduce false positives but may miss difficult faces.

Drawing Detection Results

Each detection is represented by:

x, y, width, height

A rectangle can be drawn around each face:

for x, y, w, h in faces_rect:
    cv.rectangle(
        img,
        (x, y),
        (x + w, y + h),
        (0, 255, 0),
        thickness=2
    )

The number of detections is:

len(faces_rect)

Limitations of Haar Cascades

Haar cascades are convenient and require little setup, but they can be sensitive to:

  • Noise

  • Poor lighting

  • Non-frontal faces

  • Hats and glasses

  • Unusual poses

  • Background structures resembling faces

A cascade may therefore detect false positives, such as body regions or other shapes that resemble facial patterns. Increasing minNeighbors can reduce false detections, but excessive increases may cause real faces to be missed.

For video, the same detection process can be applied to every frame.


18. Face Recognition with OpenCV

Face recognition requires a labeled training set. The example data contains several folders, with each folder representing one person and containing multiple images of that person.

The recognition process consists of:

  1. Preparing labeled face images.

  2. Detecting faces in those images.

  3. Extracting face regions.

  4. Assigning numerical labels.

  5. Training a recognizer.

  6. Saving the trained model.

  7. Loading the model later.

  8. Predicting the identity of new faces.

Features and Labels

Two lists are created:

  • Features: arrays containing detected face images.

  • Labels: numerical identifiers corresponding to the people.

A mapping is created between names and numbers. For example:

  • The first person in the name list receives label 000.

  • The second person receives label 111.

  • The third receives label 222.

Numerical labels are easier for the model to process than strings.

Preparing Training Data

For every person:

  1. Locate the person’s folder.

  2. Read each image.

  3. Convert the image to grayscale.

  4. Detect faces with a Haar cascade.

  5. Crop each detected face.

  6. Add the cropped face to the features list.

  7. Add the person’s numerical label to the labels list.

A detected face region can be extracted using:

face_region = gray[y:y+h, x:x+w]

The feature and label lists are converted to NumPy arrays before training.

Local Binary Pattern Histogram Recognizer

OpenCV provides an LBPH face recognizer:

face_recognizer = cv.face.LBPHFaceRecognizer_create()

The recognizer is trained with:

face_recognizer.train(features, labels)

The training set must contain corresponding features and labels.

Saving the Model

A trained recognizer can be saved to a YAML file:

face_recognizer.save("face_trained.yml")

Saving makes it possible to use the trained model later without repeating the entire training process.

The numerical arrays can also be saved separately, for example as NumPy files.

Making Predictions

The saved recognizer is loaded with:

face_recognizer.read("face_trained.yml")

For a new image:

  1. Read the image.

  2. Convert it to grayscale.

  3. Detect faces.

  4. Crop each face.

  5. Pass the face region to the recognizer.

Prediction:

label, confidence = face_recognizer.predict(face_region)

The output includes:

  • A predicted numerical label.

  • A confidence-like score.

The numerical label is mapped back to a person’s name using the original name list.

The detected face and predicted name can then be displayed with a rectangle and text.

Limitations

A small training set may produce unreliable recognition. A dataset with only a few dozen images per person is generally insufficient for a robust recognizer.

Recognition quality can also be affected by:

  • Similar-looking individuals

  • Different poses

  • Lighting changes

  • Accessories

  • Poorly cropped faces

  • Low image quality

  • Insufficient variation in training images

Confidence values should be interpreted cautiously. A high or unusual score does not necessarily guarantee a correct prediction.


19. Deep-Learning Image Classification

A deep-learning model can be used to classify images into multiple categories. The example task is classifying characters from The Simpsons.

Deep learning is often more powerful than traditional recognition methods when sufficient data and computing resources are available.

Dataset Organization

The dataset contains folders, where each folder represents a character. Each folder contains multiple images.

A typical dataset may contain classes with different numbers of images. The most frequent classes can be selected to create a balanced, manageable classification problem.

The workflow is:

  1. Count images in each character folder.

  2. Sort classes by the number of images.

  3. Select the top classes.

  4. Read and preprocess their images.

  5. Train a classifier.

GPU Acceleration

Training deep-learning networks can be computationally expensive. A GPU, or graphics processing unit, can accelerate the calculations.

Cloud notebook platforms may provide free GPU access. GPU availability must generally be enabled in the notebook settings.

Image Size and Channels

Neural networks require consistent input dimensions. Every image must be resized to the same size, such as:

80×8080 \times 8080×80

The example uses one grayscale channel rather than three color channels:

Image size: 80 × 80
Channels: 1

Using grayscale reduces the amount of data and focuses the model on shape and structure rather than color.

Creating the Dataset

A preprocessing utility can:

  • Loop through character folders.

  • Read each image.

  • Resize it.

  • Convert it to grayscale.

  • Assign a numerical class label.

  • Store the result in a training set.

The result is conceptually a collection of pairs:

(image array, class label)

The image arrays are features, while the labels identify the characters.

Separating Features and Labels

The training set is split into:

  • Feature arrays.

  • Labels.

The feature arrays are reshaped into a four-dimensional tensor suitable for a convolutional network. The usual organization is conceptually:

(number of examples, height, width, channels)

Normalization

Pixel values commonly range from 000 to 255255255. Normalization scales them to the range 000 to 111:

xnormalized=x255x_{\text{normalized}} = \frac{x}{255}xnormalized​=255x​

Normalized inputs generally allow a network to learn more efficiently.

One-Hot Encoding

Class labels initially represented as integers can be converted into one-hot vectors.

For example, if there are four classes, class 222 may be represented as:

[0,0,1,0][0, 0, 1, 0][0,0,1,0]

One-hot encoding is appropriate for multiclass classification because the output layer produces one value for each class.

Training and Validation Sets

The dataset is divided into:

  • Training data: used to update model parameters.

  • Validation data: used to evaluate performance during training.

With a validation ratio of 0.20.20.2:

  • Approximately 80%80\%80% of the data is used for training.

  • Approximately 20%20\%20% is used for validation.

Validation data is not used to directly update the model’s weights.

Data Augmentation

An image-data generator can create modified versions of existing images. This process is called data augmentation.

Augmentation introduces variation and may include transformations such as:

  • Small rotations

  • Shifts

  • Zooms

  • Flips

  • Other image modifications

It can reduce overfitting by preventing the model from memorizing only the exact training images.

Model Architecture

A convolutional model is created using a Keras-oriented utility. The model receives:

  • Image dimensions.

  • Number of channels.

  • Number of output classes.

  • Learning-rate settings.

  • Loss function.

  • Optimization settings.

A classification model may contain millions of trainable parameters. These parameters are adjusted during training to reduce the prediction error.

Loss Function and Optimizer Settings

Binary cross-entropy was used in the example model configuration, although multiclass problems are often configured with a multiclass loss depending on the output encoding and final activation.

Additional training settings include:

  • Learning rate, controlling the size of each update.

  • Momentum, helping updates maintain useful direction.

  • Weight decay, discouraging excessively large parameters.

  • Nesterov acceleration, modifying momentum-based optimization.

  • Learning-rate scheduling, changing the learning rate during training.

Training

The model is trained using batches:

  • A batch contains a fixed number of images.

  • One epoch represents a complete pass through the training data.

  • Steps per epoch depend on dataset size and batch size.

  • Validation steps determine how much validation data is evaluated.

An example batch size is 323232, and the model may be trained for multiple epochs.

Training produces a history containing measurements such as:

  • Training loss.

  • Training accuracy.

  • Validation loss.

  • Validation accuracy.

The example achieved a baseline accuracy near 70%70\%70%, although performance can vary depending on model design, preprocessing, random initialization, data quality, and training settings.

Testing a New Image

A new image must be processed exactly like the training images:

  1. Read the image with OpenCV.

  2. Convert it to grayscale.

  3. Resize it to the required dimensions.

  4. Reshape it to include the channel and batch dimensions.

  5. Normalize it if normalization was used during training.

  6. Pass it to the model.

The model returns a probability or score for each class. The predicted class is the index with the largest output value:

c^=arg⁡max⁡cp(c∣x)\hat{c} = \arg\max_c p(c \mid x)c^=argmaxc​p(c∣x)

The index is then mapped back to the corresponding character name.

Incorrect predictions are normal when the model is small, the training data is limited, or the classes are visually similar. Deep-learning model development often requires experimenting with:

  • Architecture

  • Number of layers

  • Dataset size

  • Image resolution

  • Data augmentation

  • Learning rate

  • Number of epochs

  • Loss function

  • Class balance

Deep learning is widely used in applications such as:

  • Self-driving vehicles

  • Medical diagnosis

  • Object recognition

  • Face recognition

  • Image classification

  • Automated inspection

A complete computer-vision system typically combines image preprocessing, feature extraction, model training, prediction, and visualization.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent