# Example code for: # Gradient calculation (emboss) in the horizontal direction using a # super simple [-3,0,3] style filter. # # Jay Summet 2024 # #Python 3.10, OpenCV 4.5.x # import cv2 import numpy as np def scaleTo8Bit(image, displayMin = None, displayMax=None ): if displayMin == None: displayMin = np.min(image) if displayMax == None: displayMax = np.max(image) np.clip(image, displayMin, displayMax, out=image) image = image - displayMin cf = 255. / (displayMax - displayMin) imageOut = ( cf * image).astype(np.uint8) return imageOut #Load source / input image as grayscale, also works on color images... imgIn = cv2.imread("blueSky.jpg", cv2.IMREAD_GRAYSCALE) cv2.imshow("Original", imgIn) #Convert to floating point so our output of filter2D will also be floating #point image. (To preserve full 255...0...-255 range.) imgIn = imgIn.astype(np.float32) #Create the filter kernel = np.zeros( (1,2), np.float32) kernel[0,0] = -3.0 #Try 2.0 kernel[0,1] = 3.0 #Try 2.0 #A square filter you can also try... #kernel = np.zeros( (3,3), np.float32) #kernel[1,0] = -0.5 #Try -1.5 #kernel[1,2] = 0.5 #Try 1.5 #Do the actual kernel operation... output = cv2.filter2D(imgIn, -1, kernel) cv2.imshow("not scaled", output) #cv2.imwrite("incorrect-scaling-example.png", output) #Scaling back so that the zero point is at 128 (gray)... output8bit = scaleTo8Bit(output) cv2.imshow("Emboss H", output8bit) cv2.waitKey(0) cv2.startWindowThread()