📷

OpenCV in Python Tutorial Series

Jul 23, 2024

OpenCV in Python Tutorial Series

Introduction to OpenCV

  • OpenCV: Open source computer vision library used for image and video analysis, processing, and manipulation.
  • Common uses: Image loading, drawing, facial detection, recognition, object detection, object tracking.
  • Target audience: Python users; no need for extensive machine learning knowledge.
  • Content scope: Basics to advanced techniques over multiple videos.

Installing OpenCV

  • Requirements: Python, PIP (PIP3 for Mac/Linux).
  • Install commands:
    • pip install opencv-python
    • Alternatives if PIP doesn’t work:
      • python -m pip install opencv-python
      • python3 -m pip install opencv-python
  • Note: OpenCV may automatically install NumPy.

Setting Up the Project

  • Create a project folder, e.g., opencv_tutorial.
  • Inside the folder:
    • Create a Python file, e.g., tutorial1.py.
    • Create an assets folder containing images and videos.
  • Use a code editor (e.g., Sublime Text).

Basic Image Operations

  1. Import OpenCV: import cv2 as cv (Note: cv2 is used instead of opencv-python).
  2. Load an Image:
    • Image path: path/to/image.jpg.
    • Use modes:
      • Default (Color): cv.IMREAD_COLOR or -1
      • Grayscale: cv.IMREAD_GRAYSCALE or 0
      • Unchanged: cv.IMREAD_UNCHANGED or 1
    • Example: img = cv.imread('assets/logo.jpg', cv.IMREAD_GRAYSCALE)
  3. Display an Image:
    • Show Image: cv.imshow('Window Name', img)
    • Wait for Key: cv.waitKey(0) (0 means wait indefinitely until a key is pressed).
    • Close Windows: cv.destroyAllWindows()

Image Manipulation

  1. Resize an Image:
    • Using fixed dimensions: resized_img = cv.resize(img, (400, 400))
    • Using scale factors: resized_img = cv.resize(img, (0, 0), fx=0.5, fy=0.5)
  2. Rotate an Image:
    • Clockwise 90°: rotated_img = cv.rotate(img, cv.ROTATE_90_CLOCKWISE)
    • Counter-clockwise 90°: rotated_img = cv.rotate(img, cv.ROTATE_90_COUNTERCLOCKWISE)

Writing an Image

  • Save an Image: cv.imwrite('new_image.jpg', img)
  • Example output folder management: A new file new_image.jpg will be created in the same directory.

Summary

  • Covered basics: loading, displaying, resizing, rotating, and saving images using OpenCV.
  • Next steps: Move towards more advanced image and video manipulations in future tutorials.

Sponsor Mention

  • AlgoExpert: Platform for preparing software engineering coding interviews.
  • Promo code: TECHWITHTIM for a discount.

Call to Action

  • Engagement: Encouraged to like, subscribe, and comment on what specific topics to cover next.