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

Speaker 1Speaker 2

Python OpenCV Computer Vision

14:28
0:00-14:28
  1. Corey

    Welcome to our Python and OpenCV course. OpenCV is a computer vision library available in Python, C++, and Java. Computer vision uses images and video to derive useful information, and in this course we move from basic media handling all the way to face recognition and deep learning.

  2. Michael

    The roadmap is broad but logical. We begin by reading images and video, resizing them, transforming them, drawing shapes, and adding text. Then we cover color spaces, bitwise operators, masking, histograms, thresholding, edge detection, and contours. Finally, we detect and recognize faces, and build a deep learning model that classifies Simpsons characters.

  3. Corey

    Before installing OpenCV, check that Python is available by running Python dash dash version in a terminal. The course recommends Python 3.7 or newer, rather than older Python versions or Python 2. Then install the main package with pip install OpenCV contrib Python.

  4. Michael

    The contrib package includes the main OpenCV modules plus community-contributed modules, so it provides more functionality than installing only OpenCV Python. NumPy will also be installed or used because it supports scientific computing and array operations such as reshaping and matrix manipulation.

  5. Corey

    The course also recommends installing Seer, a utility package designed to speed up computer vision workflows with helper functions. It is used more heavily in the final deep learning project, but installing it at the beginning avoids an extra setup step later. The course materials and code are made available through the instructor's GitHub repository.

  6. Michael

    To read an image, import cv2 and call cv2.imread with an image path. The result is an image represented as a matrix of pixels. You can display it with cv2.imshow, giving the window a name and passing in the image matrix.

  7. Corey

    After displaying a window, cv2.waitKey controls how long OpenCV waits for keyboard input. A value of zero means wait indefinitely, which is useful for keeping a still image window open until a key is pressed. Relative paths work when the media file is inside the current working directory, although absolute paths can be used too.

  8. Michael

    Large images may extend beyond the monitor because basic OpenCV display does not automatically resize them to fit the screen. That is why resizing and rescaling are important—not only for display, but also because large media files require more processing.

  9. Corey

    Videos are read differently. Create a cv2.VideoCapture object, passing either a video-file path or a camera index. Index zero usually refers to the webcam, while one, two, and so on can refer to additional cameras.

  10. Michael

    For a video file, repeatedly call capture.read inside a loop. It returns a Boolean indicating whether a frame was successfully read and the current frame itself. Display each frame with cv2.imshow, and use a keyboard condition—such as checking whether the letter D was pressed—to break out of the loop.

  11. Corey

    When the loop ends, release the capture object and destroy the OpenCV windows. If OpenCV reports an assertion failure, a common cause is that it could not find the requested image, video, or next video frame. A video reaching its final frame can produce this situation if the loop does not stop cleanly.

  12. Michael

    Rescaling reduces computational strain by changing an image or frame's width and height. A typical helper function takes a frame and a scale value, reads width from frame.shape[1] and height from frame.shape[0], multiplies both by the scale, converts the results to integers, and calls cv2.resize.

  13. Corey

    The rescaling function works for images, saved videos, and live video frames. There is also capture.set: property three represents width and property four represents height. That method is specifically useful for live camera input, while a resize function should be used for existing image or video files.

  14. Michael

    OpenCV can draw on an existing image or on a blank NumPy array. A blank image can be created with NumPy zeros, using a height, width, and color-channel shape, plus an image data type such as unsigned 8-bit integers. Assigning pixel values across the array can fill the image with a color.

  15. Corey

    The main drawing functions are cv2.rectangle, cv2.circle, and cv2.line. Rectangles and circles receive coordinates, a color in OpenCV's BGR order, and a thickness. A thickness of negative one fills the shape; otherwise, the value controls the border thickness.

  16. Michael

    Text is added with cv2.putText. You provide the words, their starting position, a built-in font such as a Hershey font, a font scale, color, and thickness. Coordinates and font size matter because text can easily extend beyond the visible area of a large image.

  17. Corey

    Several basic operations appear in nearly every computer vision project. Converting BGR to grayscale with cv2.cvtColor leaves only pixel-intensity information. Gaussian blur reduces image noise, often caused by lighting or camera sensors, and its kernel size must use odd numbers such as three by three or seven by seven.

  18. Michael

    The Canny detector identifies edges using threshold values. Blurring before Canny generally reduces the number of detected edges because small noisy details disappear. Dilation thickens a binary or edge image using a structuring element, while erosion shrinks regions and can sometimes restore a dilated image closer to its original form.

  19. Corey

    Images are arrays, so array slicing provides a simple way to crop them. Resizing uses cv2.resize and a destination size. Area interpolation is useful when shrinking, while linear or cubic interpolation can be used when enlarging; cubic is slower but can produce higher quality.

  20. Michael

    The basic geometric transformations are translation, rotation, resizing, flipping, and cropping. Translation shifts an image along the x and y axes using a two-by-three matrix: negative x moves left, positive x moves right, negative y moves up, and positive y moves down.

  21. Corey

    Rotation uses cv2.getRotationMatrix2D and cv2.warpAffine. You can rotate around the image center or specify another point, and positive or negative angles determine the direction. Rotating can introduce black triangular regions where no original pixels exist, so rotating repeatedly can compound those empty areas.

  22. Michael

    For flipping, cv2.flip uses a flip code: zero flips vertically, one flips horizontally, and negative one flips both vertically and horizontally. Cropping again relies on selecting a rectangular range of rows and columns through array slicing.

  23. Corey

    Contours are boundaries formed by continuous points around objects. They are mathematically different from edges, although edges are a useful intuition. Contours support shape analysis and object detection, and cv2.findContours can return external contours, all contours, or hierarchical contours.

  24. Michael

    The contour approximation method controls how much detail is retained. Chain approximation with no compression keeps contour points, while the simple approximation compresses unnecessary points—for example, representing a straight line with its two endpoints. Contours can be drawn on a blank image using cv2.drawContours.

  25. Corey

    OpenCV normally reads images in BGR order, even though RGB is more common in other libraries. That difference matters when displaying an OpenCV image with Matplotlib: colors can appear inverted unless you convert BGR to RGB with cv2.cvtColor.

  26. Michael

    Other color spaces include grayscale, HSV, and LAB. HSV represents hue, saturation, and value and is often intuitive for describing color. LAB is another representation related to human color perception. Conversions between many spaces use cv2.cvtColor, but some conversions require an intermediate step—for example, converting grayscale to BGR before converting to HSV.

  27. Corey

    A color image contains separate blue, green, and red channels. cv2.split separates those channels, which are displayed as grayscale intensity maps: brighter regions contain more of that channel's intensity. cv2.merge combines the channels again to reconstruct the color image.

  28. Michael

    Blurring is more than one operation. Averaging replaces a center pixel with an average of surrounding pixels inside a kernel window. Gaussian blur gives surrounding pixels different weights, usually producing a more natural result. Median blur uses the median and is useful for reducing certain noise, including salt-and-pepper noise.

  29. Corey

    Bilateral filtering is designed to blur while preserving edges. Its parameters include the neighborhood diameter, a color sigma, and a space sigma. Larger values allow more colors or more distant pixels to influence the calculation, so excessive values can create a washed or smudged appearance.

  30. Michael

    Bitwise operations work on binary pixel information. Bitwise AND returns the intersection of two shapes, OR returns both intersecting and non-intersecting regions, XOR returns the non-intersecting regions, and NOT inverts black and white pixels. These operations become especially useful when constructing masks.

  31. Corey

    Masking focuses processing on a selected part of an image. A mask is commonly a binary image with the same dimensions as the source image. You can draw a circle, rectangle, or combined shape on the mask, then use bitwise AND to keep only the source pixels inside that shape.

  32. Michael

    Histograms show the distribution of pixel intensities. A grayscale histogram plots intensity values from zero through 255 against the number of pixels at each value. Color histograms calculate distributions separately for the blue, green, and red channels, and a mask can restrict the histogram to a selected image region.

  33. Corey

    Thresholding converts an image into a binary representation. With simple thresholding, pixels below a chosen threshold become zero and pixels above it become the selected maximum value, commonly 255. Inverse binary thresholding reverses that relationship.

  34. Michael

    Simple thresholding requires manually selecting the threshold value. Adaptive thresholding calculates a local threshold for neighborhoods across the image, using methods such as a neighborhood mean or Gaussian-weighted calculation. That can work better when lighting varies across the image, and parameters such as block size and the constant subtracted from the local mean let you tune the result.

  35. Corey

    For gradient and edge detection, the Laplacian calculates image gradients and can produce a pencil-sketch-like edge representation. Sobel computes gradients in the x and y directions separately, and those results can be combined with a bitwise OR. Canny is a more advanced multi-step detector and often produces cleaner edges.

  36. Michael

    Face detection and face recognition are different. Detection asks whether and where a face is present; recognition asks whose face it is. A classifier decides whether an image region is positive or negative, and OpenCV provides pretrained Haar cascade classifiers for faces, eyes, smiles, full bodies, and other objects.

  37. Corey

    To detect faces with a Haar cascade, load the XML classifier using cv2.CascadeClassifier, convert the image to grayscale, and call detectMultiScale. The result contains rectangular face coordinates. Loop over those coordinates to draw rectangles around detected faces.

  38. Michael

    Haar cascades can be sensitive to noise and may mistake face-like regions for faces. The scale factor and minimum-neighbors parameter affect the result: increasing minimum neighbors can reduce false detections, while lower values may detect more faces but become more sensitive to noise. The same process can be applied frame by frame to video.

  39. Corey

    For recognition, the course uses OpenCV's built-in LBPH face recognizer. The training data contains folders for different people, with multiple images in each folder. Each detected face becomes a feature array, and its person's folder index becomes the numerical label.

  40. Michael

    After converting features and labels to NumPy arrays, train the recognizer with the feature images and labels. Save the trained model to a YAML file, along with the feature and label arrays if needed. Later, load the YAML model, detect a face in a new image, and call predict to obtain a label and confidence value.

  41. Corey

    The recognition results can vary substantially. The example used only about one hundred training images across several people, which is small for a recognition system, and the built-in recognizer is not always reliable. More training images and better models can improve results, but confidence values should still be interpreted carefully.

  42. Michael

    The final project uses a deep learning model to classify Simpsons characters. A deep model generally needs far more data than the small face-recognition example—ideally hundreds or thousands of images per class. The dataset contains folders of character images, and the project selects the ten characters with the most examples.

  43. Corey

    OpenCV handles the image preprocessing: images are read, converted to grayscale, and resized to a common size such as 80 by 80. The data is then organized into feature arrays and numerical labels, normalized so pixel values are in a useful range, and one-hot encoded for multi-class classification.

  44. Michael

    The data is split into training and validation sets, with the example assigning twenty percent to validation. An image data generator can create additional variations from existing images, which introduces randomness during training. The model is trained in batches for multiple epochs, while callbacks can schedule changes to the learning rate.

  45. Corey

    The example uses TensorFlow's Keras implementation and a utility package called Conero to create and compile the model. A GPU can speed up training, and the course demonstrates using Kaggle notebooks, where a GPU can be enabled and the Simpsons dataset attached.

  46. Michael

    Once trained, the model can classify a new image: OpenCV reads it, the same grayscale conversion and resizing are applied, and the prepared image is passed to model.predict. The predicted class index is mapped back to the character name. The demonstrated model reached a baseline accuracy around seventy percent, although results can vary with the architecture and training setup.

  47. Corey

    So the central workflow is clear: represent media as arrays, preprocess it consistently, transform or analyze its pixels, and then use increasingly advanced methods to extract information. OpenCV supplies the image and video operations, while NumPy supports the underlying arrays and deep learning tools can build classifiers on top.

  48. Michael

    That takes us from opening a cat image and drawing a rectangle all the way to detecting faces, recognizing people, and classifying Simpsons characters. The code and supporting material are available through the course GitHub repository, and the utility packages introduced here become more useful as computer vision projects grow more advanced.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent