#Using Sobel and SCHAAR kernels to calculate image gradient magnatude. # # # Jay Summet # CS 4475 2024 # #Python 3.10, OpenCV 4.5.x import cv2 import numpy as np #Used for final output display 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 A = cv2.imread("A.jpg", cv2.IMREAD_GRAYSCALE) cv2.imshow("A", A) Aflt = A.astype(float) #Calculate the X and Y first derivatives separately. #Same bit depth as original, first derivative X, 3x3 kernel. #Can also use (-1) instead of size 3 sobel kernel to use a SCHARR kernel. GradX = cv2.Sobel(Aflt, -1, 1,0,3) #Same bit depth as original, first derivative Y, 3x3 kernel. GradY = cv2.Sobel(Aflt, -1, 0,1,3) #Square them. GradX = cv2.multiply(GradX, GradX) GradY = cv2.multiply(GradY, GradY) #Add the result and take the square root. GM = cv2.add(GradY,GradX) GM = cv2.pow(GM, 0.5) gm8bit = scaleTo8Bit(GM) cv2.imshow("GM", gm8bit) cv2.imwrite("A-GM.png", gm8bit) cv2.waitKey(0) cv2.startWindowThread()