📘Getting Started with Python and OpenCV

Tejas ShahaTejas Shaha
2 min read

A Step-by-Step Guide 📷

Are you interested in computer vision, image processing, or creating cool projects with Python? OpenCV is your go-to library! Here's a step-by-step guide to get you started, complete with installation instructions and code examples. Let's dive in!

Step 1: Installation
First, make sure you have Python installed. If not, download and install it from python.org. You'll also need pip for package management.

Now, let's install OpenCV. Open your command prompt (or terminal) and run:

pip install opencv-python

Step 2: Import OpenCV
In your Python script, import OpenCV:

import cv2

Step 3: Loading and Displaying an Image
Load an image from your file system and display it:

image = cv2.imread('your_image.jpg')
cv2.imshow('Your Image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()

Step 4: Basic Image Operations
Perform basic operations like resizing, converting to grayscale, and saving:

# Resize the image
resized_image = cv2.resize(image, (width, height))

# Convert to grayscale
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Save the processed image
cv2.imwrite('output_image.jpg', gray_image)

Step 5: Drawing on Images
You can draw shapes, lines, and text on images:

cv2.line(image, (x1, y1), (x2, y2), (0, 0, 255), 2) # Draw a red line
cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2) # Draw a green rectangle
cv2.putText(image, 'Hello, OpenCV!', (x, y), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)

Step 6: Video Processing
You can also process video streams with OpenCV. Capture video from your webcam:

cap = cv2.VideoCapture(0)
while True:
 ret, frame = cap.read()
 cv2.imshow('Webcam Feed', frame)
 if cv2.waitKey(1) & 0xFF == ord('q'):
 break
cap.release()
cv2.destroyAllWindows()

There you have it! A quick guide to kickstart your journey with Python and OpenCV. Explore more features, experiment, and build exciting projects. The possibilities are endless! 🌟

0
Subscribe to my newsletter

Read articles from Tejas Shaha directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Tejas Shaha
Tejas Shaha