Header Ads Widget

⚡ Premium Tools Hub • EXE Apps + Full Python Source Code
Lite • Pro • Bundle Packs • Instant Download

OpenCV-Python Quick Guide: Complete Beginner to Advanced Computer Vision Tutorial

OpenCV-Python - Quick Guide

OpenCV (Open Source Computer Vision Library) is one of the most popular libraries for computer vision, machine learning, and image processing. Combined with Python, OpenCV provides powerful tools for building applications that can analyze images, process videos, detect objects, recognize faces, and much more.

This quick guide covers the essential OpenCV-Python concepts and functions that every beginner should know.


What is OpenCV?

OpenCV is an open-source library designed for:

  • Image Processing
  • Video Processing
  • Object Detection
  • Face Recognition
  • Motion Tracking
  • Machine Learning
  • Artificial Intelligence Applications

Key advantages include:

  • Free and Open Source
  • Cross-platform support
  • Fast and optimized performance
  • Extensive documentation
  • Large community support

Installing OpenCV

Install OpenCV using pip:

pip install opencv-python

For additional modules:

pip install opencv-contrib-python

Verify installation:

import cv2

print(cv2.__version__)

Reading an Image

Load an image from disk:

import cv2

img = cv2.imread("image.jpg")

cv2.imshow("Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Writing an Image

Save an image to disk:

cv2.imwrite("output.jpg", img)

Image Properties

Get image dimensions and channels:

print(img.shape)
print(img.size)
print(img.dtype)

Example output:

(720, 1280, 3)
2764800
uint8

Resize an Image

resized = cv2.resize(img, (640, 480))

Rotate an Image

rotated = cv2.rotate(
img,
cv2.ROTATE_90_CLOCKWISE
)

Convert Color Spaces

Convert image to grayscale:

gray = cv2.cvtColor(
img,
cv2.COLOR_BGR2GRAY
)

Convert to HSV:

hsv = cv2.cvtColor(
img,
cv2.COLOR_BGR2HSV
)

Drawing Shapes

Draw a rectangle:

cv2.rectangle(
img,
(50, 50),
(300, 200),
(0, 255, 0),
2
)

Draw a circle:

cv2.circle(
img,
(200, 200),
100,
(255, 0, 0),
3
)

Adding Text

cv2.putText(
img,
"OpenCV",
(50,100),
cv2.FONT_HERSHEY_SIMPLEX,
1,
(0,255,0),
2
)

Image Thresholding

gray = cv2.cvtColor(
img,
cv2.COLOR_BGR2GRAY
)

ret, thresh = cv2.threshold(
gray,
127,
255,
cv2.THRESH_BINARY
)

Image Filtering

Gaussian Blur:

blur = cv2.GaussianBlur(
img,
(5,5),
0
)

Median Blur:

median = cv2.medianBlur(
img,
5
)

Edge Detection

Canny Edge Detector:

edges = cv2.Canny(
img,
100,
200
)

Contour Detection

contours, hierarchy = cv2.findContours(
thresh,
cv2.RETR_TREE,
cv2.CHAIN_APPROX_SIMPLE
)

cv2.drawContours(
img,
contours,
-1,
(0,255,0),
2
)

Histogram Calculation

hist = cv2.calcHist(
[img],
[0],
None,
[256],
[0,256]
)

Reading Video Files

cap = cv2.VideoCapture(
"video.mp4"
)

while cap.isOpened():
ret, frame = cap.read()

if not ret:
break

cv2.imshow("Video", frame)

if cv2.waitKey(25) == 27:
break

cap.release()
cv2.destroyAllWindows()

Capture Video from Camera

cap = cv2.VideoCapture(0)

while True:
ret, frame = cap.read()

cv2.imshow("Webcam", frame)

if cv2.waitKey(1) == 27:
break

cap.release()
cv2.destroyAllWindows()

Save Video

fourcc = cv2.VideoWriter_fourcc(*'XVID')

out = cv2.VideoWriter(
'output.avi',
fourcc,
20.0,
(640,480)
)

Face Detection

Load Haar Cascade:

face_cascade = cv2.CascadeClassifier(
cv2.data.haarcascades +
'haarcascade_frontalface_default.xml'
)

Detect faces:

faces = face_cascade.detectMultiScale(
gray,
1.1,
5
)

Draw detection boxes:

for (x,y,w,h) in faces:
cv2.rectangle(
img,
(x,y),
(x+w,y+h),
(0,255,0),
2
)

Feature Detection with ORB

orb = cv2.ORB_create()

kp, des = orb.detectAndCompute(
gray,
None
)

Draw keypoints:

result = cv2.drawKeypoints(
img,
kp,
None
)

Feature Matching

bf = cv2.BFMatcher(
cv2.NORM_HAMMING,
crossCheck=True
)

matches = bf.match(
des1,
des2
)

Template Matching

result = cv2.matchTemplate(
image,
template,
cv2.TM_CCOEFF_NORMED
)

Morphological Transformations

Erosion:

erosion = cv2.erode(
img,
kernel,
iterations=1
)

Dilation:

dilation = cv2.dilate(
img,
kernel,
iterations=1
)

Fourier Transform

Convert image into frequency domain:

dft = cv2.dft(
np.float32(gray),
flags=cv2.DFT_COMPLEX_OUTPUT
)

Image Pyramids

Downsample image:

lower = cv2.pyrDown(img)

Upsample image:

higher = cv2.pyrUp(lower)

Machine Learning with KNN

Create KNN classifier:

knn = cv2.ml.KNearest_create()

Train model:

knn.train(
trainData,
cv2.ml.ROW_SAMPLE,
responses
)

Common OpenCV Applications

OpenCV is widely used in:

  • Face Recognition
  • Object Detection
  • License Plate Recognition
  • Medical Imaging
  • Robotics
  • Autonomous Vehicles
  • Augmented Reality
  • Surveillance Systems
  • OCR Applications
  • Gesture Recognition

Best Practices

Use Grayscale When Possible

Reduces processing time.

gray = cv2.cvtColor(
img,
cv2.COLOR_BGR2GRAY
)

Resize Large Images

Improves performance.

Release Resources

Always release camera and video objects.

cap.release()
cv2.destroyAllWindows()

Handle Errors

Check if images or videos load correctly.

if img is None:
print("Image not found")

OpenCV Learning Roadmap

Beginner Level

  • Reading Images
  • Writing Images
  • Drawing Shapes
  • Thresholding
  • Filtering

Intermediate Level

  • Contours
  • Histograms
  • Video Processing
  • Face Detection
  • Feature Detection

Advanced Level

  • Object Tracking
  • Image Stitching
  • Machine Learning
  • Deep Learning
  • Real-Time AI Applications

Conclusion

OpenCV-Python is one of the most powerful and beginner-friendly libraries for computer vision and image processing. From basic image manipulation to advanced AI-powered applications, OpenCV provides everything needed to build professional computer vision projects.

Master the fundamentals covered in this quick guide, and you'll be ready to explore advanced topics such as object detection, facial recognition, deep learning, image segmentation, and real-time computer vision systems.




Post a Comment

0 Comments