To get started with OpenCV for image processing, here's a practical example that demonstrates common tasks like grayscale conversion, blurring, edge detection, and saving results.
Step 1: Install OpenCV
First, install the OpenCV library using pip:
pip install opencv-python
Step 2: Image Processing Code
This code reads an image, applies basic filters, and displays/saves the results:
import cv2
# Replace with your image path (e.g., 'photo.jpg' or full path like 'C:/images/input.png')
IMAGE_PATH = "input.jpg"
# Read the image (OpenCV reads in BGR format)
img = cv2.imread(IMAGE_PATH)
# Check if the image was loaded successfully
if img is None:
print(f"Error: Could not read the image from {IMAGE_PATH}")
else:
# 1. Convert to Grayscale
grayscale = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 2. Apply Gaussian Blur (reduces noise)
blurred = cv2.GaussianBlur(grayscale, (5, 5), 0) # Kernel size (5x5), sigma=0
# 3. Edge Detection (Canny algorithm)
edges = cv2.Canny(blurred, threshold1=50, threshold2=150) # Adjust thresholds as needed
# Display all results
cv2.imshow("Original Image", img)
cv2.imshow("Grayscale", grayscale)
cv2.imshow("Blurred", blurred)
cv2.imshow("Edges", edges)
# Wait for a key press (0 = wait indefinitely) and close windows
cv2.waitKey(0)
cv2.destroyAllWindows()
# Save processed images to disk
cv2.imwrite("grayscale_output.jpg", grayscale)
cv2.imwrite("blurred_output.jpg", blurred)
cv2.imwrite("edges_output.jpg", edges)
print("Processed images saved successfully!")
Key Notes:
- Image Path: Ensure your input image is in the same folder as the script, or use an absolute path (e.g.,
C:/Users/Name/Pictures/input.jpg). - Adjustments:
- Change the kernel size in
GaussianBlur(e.g.,(3,3)for lighter blur,(7,7)for heavier). - Modify
threshold1andthreshold2inCannyto get more/less edges (lower values = more edges).
- Change the kernel size in
- Display:
cv2.imshowopens windows for each image—press any key to close them.
This example covers core OpenCV functions and can be extended to other tasks like resizing, cropping, or object detection. Let me know if you'd like to explore a specific use case!


作者声明:本文包含人工智能生成内容。