How to Sharpen an Image Using OpenCV and Python?

Estimated read time 2 min read

In OpenCV and Python, you can sharpen an image using the filter2D function to apply a sharpening kernel to the image.

Here’s an example code that sharpens an image using OpenCV in Python:

import cv2
import numpy as np

# Load image
img = cv2.imread('image.jpg')

# Define sharpening kernel
kernel = np.array([[-1,-1,-1], [-1,9,-1], [-1,-1,-1]])

# Apply sharpening kernel
sharp_img = cv2.filter2D(img, -1, kernel)

# Display result
cv2.imshow('Sharpened Image', sharp_img)
cv2.waitKey(0)

In this example, we first load an image using the imread function from OpenCV.

Next, we define a sharpening kernel using a 3×3 numpy array. The kernel has a center value of 9 and surrounding values of -1, which emphasizes the edges in the image.

We then apply the sharpening kernel to the image using the filter2D function. The -1 argument specifies that the output image should have the same depth as the input image.

Finally, we display the sharpened image using the imshow function from OpenCV and wait for a keypress using waitKey(0).

Note that the filter2D function can also be used to apply other types of kernels for image processing, such as blurring or edge detection kernels.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply