Computer Vision Using OpenCV

3 min read

Computer Vision Using OpenCV

I’ve recently started exploring computer vision, and OpenCV is the first library I came across. It’s amazing how you can manipulate images and even interact with your webcam using just a few lines of code. Here’s what I’ve learned so far.

Installing OpenCV

First things first, you need to install OpenCV. Just run this command:

pip install opencv-python

That’s it! You’re good to go. I love how easy pip makes life!

Loading and Displaying Images

OpenCV allows you to load images in either grayscale or color. Here’s how I managed to load an image and display it:

import cv2\

Load an image in grayscale\

img = cv2.imread(‘img_folder/hello.png’, 0)\

Display the image\

cv2.imshow(‘My Image’, img)\

Wait for a key press and close\

cv2.waitKey(0)
cv2.destroyAllWindows()

If the window doesn’t pop up, double-check the file path. I wasted 10 minutes once because I spelled the folder name wrong.

Resizing, Flipping, and Saving Images

Once you load an image, you can edit it. Here’s how I resized, flipped, and saved mine:

Resize the image to 256x256 pixels\

img_resized = cv2.resize(img, (256, 256))\

Flip the image (both horizontally and vertically)\

img_flipped = cv2.flip(img_resized, -1)\

Save the flipped image\

cv2.imwrite(‘flipped_image.jpg’, img_flipped)
print(“Saved a flipped image. Looks funny!”)

Accessing the Webcam

This part was the most fun! OpenCV makes accessing the webcam super easy. I even added a screenshot feature (because why not?):

import cv2
cap = cv2.VideoCapture(0) # Open the default webcam
while True:
ret, frame = cap.read() # Read the frame
if not ret:
print(“Webcam not working. (Why me?!)“)
break
cv2.imshow(‘Webcam Feed’, frame)
key = cv2.waitKey(1)
if key % 256 == 27: # ESC to quit
print(“Quitting webcam.”)
break
elif key % 256 == 32: # SPACE to take a screenshot
cv2.imwrite(‘webcam_screenshot.jpg’, frame)
print(“Took a screenshot! Check ‘webcam_screenshot.jpg’.“)
cap.release()
cv2.destroyAllWindows()

Wrapping Up

These are the basics I’ve tried out with OpenCV. It’s pretty cool once you get started. I know there’s a lot more to explore, but hey, one step at a time!