# "Sharpen" an image by multiplying every pixel by 2, and then subtracting # the average value of the neighborhood from it. This procedure keeps the # overall image intensity unchanged, but will enhance high frequency elements # by subtracting a blurred (unsharp) version of the image from it. # #See slide number 22 from IrfanEssa-CP-02-5-Filtering.pdf # # Jay Summet 2024 # #Python 3.10, OpenCV 4.5.4 # import cv2 import numpy as np #Load source / input image as grayscale, also works on color images... imgIn = cv2.imread("oscar.jpg", cv2.IMREAD_GRAYSCALE) cv2.imshow("Original", imgIn) #Create the identity filter, but X 2 kernel = np.zeros( (9,9), np.float32) kernel[4,4] = 2.0 #Identity, times two! print(kernel) #Create a box filter: boxFilter = np.ones( (9,9), np.float32) / 81.0 #Try leaving out the /81 for fun.... print(boxFilter) #Subtract the two: kernel = kernel - boxFilter print(kernel) #Note that we are subject to overflow and underflow here...but # filter2D clips top and bottom ranges on the output when working with uint8 # images. So this is mostly fine as long as you don't have a very bright # or very dark pixel surrounded by the opposite type. If this bothers # you, work with floats and then convert back.... custom = cv2.filter2D(imgIn, -1, kernel) cv2.imshow("Sharpen with unsharp mask", custom) cv2.waitKey(0) cv2.startWindowThread()