
Image filtering is a key technique in computer vision, enabling effects like blurring, sharpening, and edge detection. Using OpenCV, we can create stunning image filters with just a few lines of code.
Step 1: Install OpenCV
Ensure OpenCV is installed by running:
pip install opencv-python numpy
Step 2: Load and Display an Image
Start by loading an image using OpenCV:
import cv2
import numpy as np
# Load the image
image = cv2.imread(“sample.jpg”)
cv2.imshow(“Original Image”, image)
cv2.waitKey(0)
cv2.destroyAllWindows()
Step 3: Apply a Blurring Filter
Blurring removes noise and smoothens images. Gaussian blur is a popular choice:
blurred = cv2.GaussianBlur(image, (15, 15), 0)
cv2.imshow(“Blurred Image”, blurred)
cv2.waitKey(0)
cv2.destroyAllWindows()
Step 4: Apply Edge Detection
Edge detection highlights object boundaries in an image:
edges = cv2.Canny(image, 100, 200)
cv2.imshow(“Edge Detection”, edges)
cv2.waitKey(0)
cv2.destroyAllWindows()
Step 5: Convert Image to Pencil Sketch
Convert an image into a pencil sketch by blending grayscale and inverted blurred images:
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
inverted = 255 – gray
blurred = cv2.GaussianBlur(inverted, (21, 21), 0)
sketch = cv2.divide(gray, 255 – blurred, scale=256)
cv2.imshow(“Pencil Sketch”, sketch)
cv2.waitKey(0)
cv2.destroyAllWindows()
Step 6: Apply a Sepia Effect
Sepia filters give images a warm, vintage look:
sepia_filter = np.array([[0.272, 0.534, 0.131],
[0.349, 0.686, 0.168],
[0.393, 0.769, 0.189]])
sepia_image = cv2.transform(image, sepia_filter)
sepia_image = np.clip(sepia_image, 0, 255)
cv2.imshow(“Sepia Effect”, sepia_image.astype(np.uint8))
cv2.waitKey(0)
cv2.destroyAllWindows()
Step 7: Apply a Cartoon Effect
Cartoonizing an image involves bilateral filtering and edge detection:
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
edges = cv2.adaptiveThreshold(cv2.medianBlur(gray, 7), 255,
cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 9, 2)
color = cv2.bilateralFilter(image, 9, 300, 300)
cartoon = cv2.bitwise_and(color, color, mask=edges)
cv2.imshow(“Cartoon Effect”, cartoon)
cv2.waitKey(0)
cv2.destroyAllWindows()
Conclusion
With OpenCV, you can apply various image filters to enhance photos, detect edges, or create artistic effects like pencil sketches and cartoons. Experiment with different filters to create visually striking transformations!