Computer Vision Beginner 12 minutes

OpenCV

The best-known open library for computer vision: reading images and video, drawing, contours, and running networks.

Your progress in the track0%

Installation

pip install opencv-python

(The opencv-python-headless version suits servers without a graphical interface.)

Images and drawing

import cv2
img = cv2.imread("street.jpg")
h, w = img.shape[:2]
cv2.rectangle(img, (50, 40), (200, 180), (0, 255, 0), 2)      # (x1, y1), (x2, y2), BGR
cv2.putText(img, "car 0.91", (50, 32), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)
cv2.imwrite("out.jpg", img)
roi = img[40:180, 50:200]          # indexing [y1:y2, x1:x2]

cv2.putText does not support Arabic shaping; to show Arabic text on images, use a drawing library that supports it.

Contours and shape analysis

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, th = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
contours, _ = cv2.findContours(th, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
    if cv2.contourArea(c) > 500:
        x, y, cw, ch = cv2.boundingRect(c)
        cv2.rectangle(img, (x, y), (x + cw, y + ch), (255, 0, 0), 2)

Video

cap = cv2.VideoCapture(0)          # the default camera, or a path to a video file
while True:
    ok, frame = cap.read()
    if not ok:
        break
    edges = cv2.Canny(cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY), 80, 160)
    cv2.imshow("edges", edges)
    if cv2.waitKey(1) & 0xFF == ord("q"):
        break
cap.release(); cv2.destroyAllWindows()

Run this example on your computer; it does not work inside the browser.

Running networks

The cv2.dnn module loads models in formats such as ONNX and runs them without PyTorch, which is useful for lightweight deployment:

net = cv2.dnn.readNetFromONNX("model.onnx")
blob = cv2.dnn.blobFromImage(img, scalefactor=1/255, size=(224, 224), swapRB=True)
net.setInput(blob)
out = net.forward()

Lesson terms

OpenCV
An open-source library with thousands of algorithms for image processing and computer vision.
Contour
A curve joining the connected points on the boundary of a region of uniform intensity, used for shape analysis.

Abstract

OpenCV is an open-source library for computer vision and image processing, written in C++ with a widely used Python interface, that handles images as NumPy arrays. It provides reading and writing of images and video, processing, drawing, contour extraction, camera calibration, and a dnn module for running trained models. The most important things to remember are the BGR channel order and (x, y) coordinates versus array indexing [row, column].

Review questions

  1. What is the difference between OpenCV coordinates and NumPy indexing?

    OpenCV drawing functions use (x, y), that is (column, row), while array indexing img[y, x] starts with the row.

  2. How do you read video frames from the device camera?

    cv2.VideoCapture(0), then read() in a loop.

Sources and references

  1. OpenCV-Python Tutorials
  2. OpenCV documentation (4.x)
  3. opencv-python on PyPI

Complete the lesson