Practical Python and
OpenCV: An Introductory,
Example Driven Guide to
Image Processing and
Computer Vision
CONT ENT S
1 introduction 1
2 python and required packages 5
2.1 NumPy and SciPy . . . . . . . . . . . . . . . . 6
2.1.1 Windows . . . . . . . . . . . . . . . . . 6
2.1.2 OSX . . . . . . . . . . . . . . . . . . . 7
2.1.3 Linux . . . . . . . . . . . . . . . . . . . 7
2.2 Matplotlib . . . . . . . . . . . . . . . . . . . . 7
2.2.1 All Platforms . . . . . . . . . . . . . . 8
2.3 OpenCV . . . . . . . . . . . . . . . . . . . . . . 8
2.3.1 Windows and Linux . . . . . . . . . . 9
2.3.2 OSX . . . . . . . . . . . . . . . . . . . 9
2.4 Mahotas . . . . . . . . . . . . . . . . . . . . . . 9
2.4.1 All Platforms . . . . . . . . . . . . . . 10
2.5 Skip the Installation . . . . . . . . . . . . . . . 10
3 loading, displaying, and saving 11
4 image basics 15
4.1 So, what’s a pixel? . . . . . . . . . . . . . . . 15
4.2 Overview of the Coordinate System . . . . . 18
4.3 Accessing and Manipulating Pixels . . . . . . 18
5 drawing 27
5.1 Lines and Rectangles . . . . . . . . . . . . . . 27
5.2 Circles . . . . . . . . . . . . . . . . . . . . . . 32
6 image processing 37
6.1 Image Transformations . . . . . . . . . . . . . 37
6.1.1 Translation . . . . . . . . . . . . . . . . 38
6.1.2 Rotation . . . . . . . . . . . . . . . . . 43
6.1.3 Resizing . . . . . . . . . . . . . . . . . 48
6.1.4 Flipping . . . . . . . . . . . . . . . . . 54
iii
Contents
6.1.5 Cropping . . . . . . . . . . . . . . . . 57
6.2 Image Arithmetic . . . . . . . . . . . . . . . . 59
6.3 Bitwise Operations . . . . . . . . . . . . . . . 66
6.4 Masking . . . . . . . . . . . . . . . . . . . . . 69
6.5 Splitting and Merging Channels . . . . . . . . 76
6.6 Color Spaces . . . . . . . . . . . . . . . . . . . 80
7 histograms 83
7.1 Using OpenCV to Compute Histograms . . . 84
7.2 Grayscale Histograms . . . . . . . . . . . . . . 85
7.3 Color Histograms . . . . . . . . . . . . . . . . 87
7.4 Histogram Equalization . . . . . . . . . . . . . 93
7.5 Histograms and Masks . . . . . . . . . . . . . 95
8 smoothing and blurring 101
8.1 Averaging . . . . . . . . . . . . . . . . . . . . . 103
8.2 Gaussian . . . . . . . . . . . . . . . . . . . . . 105
8.3 Median . . . . . . . . . . . . . . . . . . . . . . 106
8.4 Bilateral . . . . . . . . . . . . . . . . . . . . . . 109
9 thresholding 112
9.1 Simple Thresholding . . . . . . . . . . . . . . 112
9.2 Adaptive Thresholding . . . . . . . . . . . . . 116
9.3 Otsu and Riddler-Calvard . . . . . . . . . . . 120
10 gradients and edge detection 124
10.1 Laplacian and Sobel . . . . . . . . . . . . . . . 125
10.2 Canny Edge Detector . . . . . . . . . . . . . . 130
11 contours 133
11.1 Counting Coins . . . . . . . . . . . . . . . . . 133
12 where to now? 142