Sub topic 1
How OpenCV represents an image
Prerequisites
This chapter assumes you know basic Python syntax and functions, can install packages with pip, and can index NumPy arrays. You should also know that an image is a grid of pixels with a width, a height, and color channels. Install OpenCV with pip install opencv-python numpy.
How OpenCV represents an image
OpenCV stores an image as a NumPy array. A color image is a three-dimensional array with rows (height), columns (width), and channels. The shape attribute reports these in that order: (height, width, 3). The dtype is usually uint8, so each channel value runs from 0 to 255.
Reading an image and checking that it loaded
cv2.imread returns None when it cannot read a file. It does not raise an error, so check the result right away.
import cv2
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
print(img.shape) # (height, width, 3)
print(img.dtype) # uint8Displaying and saving images
cv2.imshow opens a window. cv2.waitKey(0) keeps the window open until you press a key. cv2.imwrite saves the array, and the file extension sets the format.
import cv2
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
cv2.imshow("Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imwrite("copy.png", img)BGR, RGB, and grayscale
OpenCV orders color channels as blue, green, red (BGR). Many other libraries use red, green, blue (RGB). cv2.cvtColor converts between them and also produces grayscale.
import cv2
img = cv2.imread("photo.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # shape: (height, width)
rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
b, g, r = img[0, 0] # the first pixel, in BGR orderResizing to a size or by a scale factor
cv2.resize takes the target size as (width, height), which is the reverse of shape. To scale instead, pass None as the size and set fx and fy. Use cv2.INTER_AREA when shrinking. Use cv2.INTER_CUBIC or cv2.INTER_LINEAR when enlarging.
import cv2
img = cv2.imread("photo.jpg")
h, w = img.shape[:2]
small = cv2.resize(img, (w // 2, h // 2), interpolation=cv2.INTER_AREA)
big = cv2.resize(img, None, fx=2.0, fy=2.0, interpolation=cv2.INTER_CUBIC)Exercise
An image has shape (480, 640, 3). What (width, height) tuple do you pass to cv2.resize to make it half as large?
Show answer
(320, 240). The width is 640 divided by 2, and the height is 480 divided by 2.