- Nov 15, 2025
How to Load and Display an Image in Python Using OpenCV (VSCode)
- DevTechie
- Python
Working with images is one of the most common tasks in computer vision, and OpenCV makes this process incredibly simple. In this tutorial, we’ll walk through a short Python script that loads an image from your computer and displays it in a separate window. Even if you’re new to OpenCV, this example is a great place to start.
We will be using Visual Studio Code for this example.
Importing OpenCV and OS Modules
We start by importing two modules:
cv2 — the OpenCV library used for image processing
os — helps us work with file paths in a platform-independent way
import cv2
import osBuilding the Image Path
Instead of hardcoding the full path, the script uses os.path.expanduser() to safely reference the user’s home directory. This expands the ~ symbol to your actual home folder (e.g., /Users/yourname/ on macOS or Linux). This ensures the script works reliably on different machines.
imagePath = os.path.expanduser('~/Desktop/PythonCode/sample.png')Reading the Image with OpenCV
cv2.imread() loads the image and returns it as a NumPy array, meaning every pixel is stored as numerical values.
img = cv2.imread(imagePath)If OpenCV cannot find the file or the path is incorrect, img will be None.
Before doing anything with the image, it’s good practice to verify that it was loaded properly. If the file doesn’t exist or the path is incorrect, you get a friendly error message instead of a crash.
if img is None:
print("Image not found. Check the path.")Display the Image in a Window
else:
cv2.imshow("Sample Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()Here’s what these functions do:
cv2.imshow("Sample Image", img) Opens a new window named “Sample Image” and displays the loaded image.
cv2.waitKey(0)Pauses the program and waits indefinitely for a keyboard key. Without this line, the window will close immediately.
cv2.destroyAllWindows() Closes all OpenCV windows once a key is pressed.
Complete code:
import cv2
import os
imagePath = os.path.expanduser('~/Desktop/PythonCode/sample.png')
img = cv2.imread(imagePath)
if img is None:
print("Image not found. Check the path.")
else:
cv2.imshow("Sample Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()Final Thoughts
This small script demonstrates the foundational workflow for working with images in OpenCV:
Load an image
Verify it exists
Display it in a window
Wait for user input
Safely close the window
Understanding these basics sets the stage for more advanced tasks like image transformations, filters, object detection, and real-time video processing.
Visit https://www.devtechie.com for more
