Introduction to OpenCV: Seeing in Matrices
To a computer, an image is not a picture; it is a grid of numbers. OpenCV bridges the gap between our visual perception and the machine's mathematical reality.
1. Loading and Reading Data
The function cv2.imread(filepath) is your entry point. It reads an image file and converts it into a NumPy array. If the image cannot be found, OpenCV does not throw an error; it simply returns None. Always verify your image loaded properly!
2. Displaying Images Safely
You can visualize the NumPy arrays using cv2.imshow('Window Name', img_array). However, the window will appear and disappear instantly unless paused.
You must pair it with cv2.waitKey(0), which halts execution until a keyboard event occurs. Finally, always clean up system resources by calling cv2.destroyAllWindows().
❓ Frequently Asked Questions
Why does OpenCV use BGR instead of RGB?
When OpenCV was developed by Intel in the late 1990s, the standard color format among camera manufacturers and software vendors was BGR (Blue, Green, Red). Changing it now would break decades of legacy code. If you are plotting OpenCV images with Matplotlib, you must convert them first: cv2.cvtColor(img, cv2.COLOR_BGR2RGB).
How do I install OpenCV in Python?
You can install it using pip. Run the command:
pip install opencv-pythonIf you also need extra modules (like SIFT/SURF algorithms), you should install opencv-contrib-python instead.
What are the dimensions of an OpenCV image array?
By checking image.shape, you receive a tuple: (Height, Width, Channels). A standard 1080p color image returns (1080, 1920, 3). Grayscale images drop the channel dimension entirely, returning (1080, 1920).