Computer Vision OpenCV Basics
OpenCV is a free, open-source library packed with ready-made vision tools. Researchers started the project in the late 1990s, and today it runs on phones, laptops, robots, and web servers. Developers write OpenCV code in Python, C++, or Java. Python offers the gentlest path for newcomers.
What OpenCV Gives You
Think of OpenCV as a well-stocked toolbox. Each drawer holds tools for one kind of job, so you grab the right one without building it from scratch.
+-------------------- OpenCV Toolbox --------------------+ | core arrays and basic math | | imgproc blur, edges, thresholds, shapes | | video tracking and motion | | features keypoints and matching | | dnn run trained neural networks | | highgui windows, keys, and mouse events | +--------------------------------------------------------+
Installing the Library
Open a terminal and run one command. The package name looks unusual, but the import name stays short.
pip install opencv-python numpyPython code loads the library with import cv2.
Reading, Showing, and Saving an Image
The first program loads a photo, prints its size, and writes a copy to disk.
import cv2
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Check the file path")
print(img.shape) # (height, width, channels)
cv2.imwrite("copy.jpg", img)
cv2.imshow("Preview", img)
cv2.waitKey(0)
cv2.destroyAllWindows()The imread function returns None when the path is wrong. Always test for that value, because a missing file causes confusing errors later in the script.
Images Are Arrays
OpenCV stores every image as a NumPy array. A color photo with 480 rows and 640 columns becomes a grid of shape (480, 640, 3). Each pixel holds three numbers between 0 and 255. Picking pixel values or cutting a region follows normal array rules.
pixel = img[100, 200] # one pixel: [B, G, R]
crop = img[50:250, 100:300] # rows 50-250, columns 100-300The BGR Surprise
OpenCV orders color channels as Blue, Green, Red. Most other libraries use Red, Green, Blue. Showing an OpenCV image in another tool without conversion produces strange colors, such as orange skies turning blue.
Everyday Operations
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
small = cv2.resize(img, (320, 240))
flip = cv2.flip(img, 1)
cv2.rectangle(img, (50, 50), (200, 150), (0, 255, 0), 2)
cv2.putText(img, "Hello", (50, 40),
cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)Colors in drawing functions follow BGR order too, so (0, 255, 0) draws green.
Working With Video
A video is a fast stream of images. The loop below grabs one frame at a time from a webcam.
[ Open camera ] -> [ Read frame ] -> [ Process frame ]
^ |
| v
+---- [ Show frame, check key ]
cap = cv2.VideoCapture(0)
while True:
ok, frame = cap.read()
if not ok:
break
cv2.imshow("Camera", frame)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
cap.release()
cv2.destroyAllWindows()Pressing the Q key ends the loop. Releasing the camera frees it for other programs.
Common Beginner Mistakes
- Skipping the
Nonecheck after loading an image - Forgetting that OpenCV uses BGR order
- Passing size as (height, width) to
resize, which expects (width, height) - Leaving out
waitKey, which keeps windows from refreshing - Editing the original image when a copy with
img.copy()would protect it
Practice Ideas
Load a photo, convert it to grayscale, and save both versions. Draw a rectangle around any region you choose. Open the webcam and flip the live view like a mirror. Each exercise takes only a few lines and builds the habits every later topic depends on.
Frequently Asked Questions
Which package should I install?
The package opencv-python covers the main modules and suits nearly every beginner. The package opencv-contrib-python adds experimental modules, including extra trackers and descriptors. Install only one of them in a single environment, because the two packages clash when they sit side by side.
Does OpenCV need a graphics card?
Standard OpenCV functions run on the normal processor and handle most beginner tasks smoothly. Neural network modules can use a graphics card when available, which speeds up heavy models. Laptops without special hardware work fine for every exercise in this topic.
Where do sample images come from?
Any photo from a phone works well. Public datasets such as CIFAR-10 and COCO offer thousands of free pictures for practice. Keep a small folder of test images near your script so file paths stay short and simple.
