def filter(img): # the first step to do filtering scharrx = cv2.Scharr(img, cv2.CV_64F, dx=1, dy=0) scharrx = cv2.convertScaleAbs(scharrx) scharry = cv2.Scharr(img, cv2.CV_64F, dx=0, dy=1) scharry = cv2.convertScaleAbs(scharry) result = cv2.addWeighted(scharrx, 0.5, scharry, 0.5, 0) return result
def Scharr_edge(im): im = cv2.GaussianBlur(np.asarray(im, dtype="float32"), (filtR, filtR), 0) Gx = cv2.Scharr(im, -1, 0, 1) Gy = cv2.Scharr(im, -1, 1, 0) res = cv2.magnitude(Gx, Gy) angle = np.arctan2(Gy, Gx) return res, angle
def func(path, save, interval, shape): images = os.listdir(path) images.sort() avg = np.zeros(shape) grad = np.zeros(shape) filename = 'img_cam' + path[-1] + '.jpg' for index, image in enumerate(images): img = cv2.imread(os.path.join(path, image), cv2.IMREAD_GRAYSCALE) img = cv2.GaussianBlur(img, (5, 5), 1) avg += img / interval x_grad = cv2.Scharr(img, ddepth=cv2.CV_64F, dx=True, dy=False) y_grad = cv2.Scharr(img, ddepth=cv2.CV_64F, dx=False, dy=True) gradient = np.sqrt(x_grad**2 + y_grad**2) grad += gradient / interval if index % interval == 0: cv2.imwrite(f'{save}/avg/{index}_{filename}', avg) cv2.imwrite(f'{save}/grad/{index}_{filename}', grad) avg = np.zeros(shape) grad = np.zeros(shape)
def _extract_drop_edge(gray: np.ndarray, thresh1: float, thresh2: float) -> np.ndarray: blur = cv2.GaussianBlur(gray, ksize=(5, 5), sigmaX=0) dx = cv2.Scharr(blur, cv2.CV_16S, dx=1, dy=0) dy = cv2.Scharr(blur, cv2.CV_16S, dx=0, dy=1) # Use magnitude of gradient squared to get sharper edges. grad = dx.astype(float)**2 + dy.astype(float)**2 grad /= grad.max() grad = (grad * (2**8 - 1)).astype(np.uint8) cv2.adaptiveThreshold(grad, maxValue=255, adaptiveMethod=cv2.ADAPTIVE_THRESH_GAUSSIAN_C, thresholdType=cv2.THRESH_BINARY, blockSize=5, C=0, dst=grad) # Hack: Use cv2.Canny() to do non-max suppression edge thinning. mask = _largest_connected_component(grad) edges = cv2.Canny(dx * mask, dy * mask, thresh1, thresh2) points = np.array(edges.nonzero()[::-1]) return points
def harris_det(img, k=0.04, th=0.1): g = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) Ix = cv2.Scharr(g, -1, 1, 0) Iy = cv2.Scharr(g, -1, 0, 1) Ix2 = Ix * Ix Iy2 = Iy * Iy Ixy = Ix * Iy Ix2 = cv2.GaussianBlur(Ix2, (5, 5), 0) Iy2 = cv2.GaussianBlur(Iy2, (5, 5), 0) Ixy = cv2.GaussianBlur(Ixy, (5, 5), 0) # prepare output image g = np.array((g, g, g)) g = np.transpose(g, (1, 2, 0)) # get R r = (Ix2 * Iy2 - Ixy**2) - k * ((Ix2 + Iy2)**2) # detect corner img[r >= np.max(r) * th] = [255, 0, 0] res = img.astype(np.uint8) return res
def scharr_edge(img, thresholding=True, threshold=64): """ Compute the edges of an image using the Scharr method. Parameters ---------- - img: The image on which to apply the filter - thresholding: Boolean for wether or not a thresholing is applied to the edges - threshold: The threshold at which to consider a pixel as an edge Returns ------- A opencv image with the pixel corresponding to edges set to 255 and the others set to 0 """ gradientX = cv2.Scharr(img, cv2.CV_32F, 1, 0)/4.0 gradientY = cv2.Scharr(img, cv2.CV_32F, 0, 1)/4.0 absGradientX = cv2.convertScaleAbs(gradientX) absGradientY = cv2.convertScaleAbs(gradientY) grad = cv2.addWeighted(absGradientX, 0.5, absGradientY, 0.5, 0) if thresholding: grad = clean_grad(grad, False, threshold) return grad
def computeGradient(psiHatP=None, inpaintedImage=None, filledImage=None): assert inpaintedImage is not None assert filledImage is not None assert psiHatP is not None ######################################### ## PLACE YOUR CODE BETWEEN THESE LINES ## ######################################### filled, _ = copyutils.getWindow(filledImage, (psiHatP.row(), psiHatP.col()), psiHatP.radius()) source = cv.cvtColor(inpaintedImage, cv.COLOR_BGR2GRAY) source, valid = copyutils.getWindow(source, (psiHatP.row(), psiHatP.col()), psiHatP.radius()) # make points near the front to zero # to erase the invalid derivative filled = cv.erode(filled, np.ones((3, 3))) gX = cv.Scharr(source, cv.CV_32F, 1, 0) gY = cv.Scharr(source, cv.CV_32F, 0, 1) length = gX * gX + gY * gY length[filled == 0] = 0 # find the index of derivative with longest length x, y = np.unravel_index(np.argmax(length), length.shape) Dx = gX[x, y] Dy = gY[x, y] ######################################### return Dy, Dx
def get_edge_map(img_rgb): img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY) edge_x = cv2.Scharr(img_gray, cv2.CV_64F, 1, 0) edge_y = cv2.Scharr(img_gray, cv2.CV_64F, 0, 1) edge = np.hypot(edge_x, edge_y) # normalize (Q&D) edge = ((edge / (np.max(edge)+ 1.0e-8)) * 255.0).astype('uint8') return edge
def remove_vertical_objects(polar_grid, polar_border, ddepth=cv2.CV_16S, kernel_size=1, scale=1, delta=0): """ Remove all the vertical sets of pixels """ grad_x = cv2.Scharr(polar_grid, ddepth, 1, 0, scale=scale, delta=delta, borderType=cv2.BORDER_REPLICATE) grad_y = cv2.Scharr(polar_grid, ddepth, 0, 1, scale=scale, delta=delta, borderType=cv2.BORDER_CONSTANT) grad_x = cv2.convertScaleAbs(grad_x) grad_x = cv2.bitwise_and(polar_border, grad_x) grad_y = cv2.convertScaleAbs(grad_y) grad_y = cv2.bitwise_and(polar_border, grad_y) mask = cv2.absdiff(grad_x, grad_y) res = cv2.bitwise_and(grad_y, mask) h, w = res.shape[:2] cv2.rectangle(res, (0, 0), (w, (h // 8)), (0, 0, 0), -1) cv2.rectangle(res, (0, h - (h // 8)), (w, h), (0, 0, 0), -1) return res
def preprocess(self, eye): # correct for drift linx = np.linspace(-self.xdrift, self.xdrift, self.nx) #linx = np.linspace(0, self.xdrift, self.nx) liny = np.linspace(0, 1, self.ny) xv, yv = np.meshgrid(linx, liny) xv = np.array(xv, np.uint8) img = eye + xv img = cv2.GaussianBlur(img, (5, 5), 0) # clip image, smooth and center on threshold if self.mini <= self.maxi: eye2 = np.clip(img, self.mini, self.maxi) eye2 = eye2.astype(float) - self.threshold else: eye2 = np.clip(img, self.maxi, self.mini) eye2 = self.threshold - eye2.astype(float) # edge detection ix = cv2.Scharr(img, cv2.CV_32F, 1, 0) iy = cv2.Scharr(img, cv2.CV_32F, 0, 1) eyecontour = np.sqrt(ix**2 + iy**2) eyecontour = np.minimum(eyecontour, np.array(self.maxcontour)) return eye2, eyecontour
def _quiver_data(roi): """ Calculates differential data for edge vector calculation, it outputs list of edge-pixels and corresponding derivatives :param numpy.ndarray roi: ROI in image :return: List of image-derivatives and position of edge-pixels i.e. dxs, dys, xs, ys """ height, width, channels = roi.shape edges = _extract_edges(roi) gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY) scharr_x = cv2.Scharr(gray, cv2.CV_64F, 1, 0) scharr_y = cv2.Scharr(gray, cv2.CV_64F, 0, 1) xs = [] ys = [] dxs = [] dys = [] for i in range(height): for j in range(width): if edges[i][j]: xs.append(j) ys.append(i) dxs.append(scharr_x[i][j]) dys.append(scharr_y[i][j]) return xs, ys, dxs, dys, edges
def main(): dirname = os.path.dirname(__file__) img = plt.imread(f'{dirname}/Fzu_shutong_L.jpg') draw = draw_picture(1, 3, (15, 4)) draw(1, img, '原图') dx = cv2.Scharr(img, -1, 1, 0) dy = cv2.Scharr(img, -1, 0, 1) d_img = cv2.addWeighted(dx, 0.5, dy, 0.5, 0) draw(2, d_img, 'Scharr边缘') fast = cv2.FastFeatureDetector_create( threshold=42, nonmaxSuppression=True, type=cv2.FAST_FEATURE_DETECTOR_TYPE_7_12) keypoints = None keypoints = fast.detect(img) corner_img = cv2.drawKeypoints(img, keypoints, None, color=(255, 142, 29)) draw(3, corner_img, 'Fast角点') plt.savefig(f'{dirname}/Fzu_shutong_L_ed.jpg') plt.show() save = save_picture() save(d_img, f'{dirname}/Scharr边缘.jpg', "gray") save(corner_img, f'{dirname}/Fast角点.jpg')
def bordes_scharr(img): img = np.float32(img) #utilizar las funciones de openCV img_horiz = cv.Scharr(img, cv.CV_32F, 1, 0) img_vert = cv.Scharr(img, cv.CV_32F, 0, 1) #graficar para ver resultados parciales plt.figure() plt.subplot(121), plt.imshow( img_horiz, 'gray'), plt.title('bordes scharr horizontales') plt.subplot(122), plt.imshow(img_vert, 'gray'), plt.title('bordes scharr verticales') plt.show() #calcular la magnitud del gradiente img_result = np.copy(img_horiz) img_result = np.abs(img_result) + np.abs(img_vert) img_result = img_result / 2 img_result = np.uint8(img_result) #se binariaza la imagen res, img_result = cv.threshold(img_result, 40, 256, cv.THRESH_BINARY) return img_result
def average_grad_Scharr(image): """ 计算图像平局梯度 @param image: @return: """ sum_grad = 0 scharrx = cv2.Scharr(image, cv2.CV_64F, 1, 0) scharrx = cv2.convertScaleAbs(scharrx) # print(scharrx) scharry = cv2.Scharr(image, cv2.CV_64F, 0, 1) scharry = cv2.convertScaleAbs(scharry) # print(scharry) scharrxy = cv2.addWeighted(scharrx, 1, scharry, 1, 0) # print(scharrxy) # cv2.imshow('a', image) cv2.imshow('scharrx', scharrx) cv2.imshow('scharry', scharry) cv2.imshow('scharrxy', scharrxy) for i in range(len(scharrxy)): for j in range(i): sum_grad += scharrxy[i][j] # print(sum_grad) aver_grad = int(sum_grad) // (480 * 640) return aver_grad
def main(img_path): """ 预处理图片, 然后展示 T = 0.05 :param img_path: :param disnoising: :return: blurry_res 模糊程度 """ gray_img = cv.imread(img_path, 0) t1 = time.time() scharr_dx = cv.Scharr(gray_img, cv.CV_64F, 1, 0) scharr_dy = cv.Scharr(gray_img, cv.CV_64F, 0, 1) scharr_img = cv.addWeighted(scharr_dx, 0.5, scharr_dy, 0.5, 0) laplacian = cv.Laplacian(gray_img, cv.CV_64F) abs_lap64f = np.absolute(laplacian) scharr_std = scharr_img.std() lap_std = laplacian.std() abs_lap_std = abs_lap64f.std() disnoy_img = cv.fastNlMeansDenoising(gray_img, h=3, templateWindowSize=7, searchWindowSize=21) # T=0.1 ~ 0.01 di_scharr_dx = cv.Scharr(disnoy_img, cv.CV_64F, 1, 0) di_scharr_dy = cv.Scharr(disnoy_img, cv.CV_64F, 0, 1) di_scharr_img = cv.addWeighted(di_scharr_dx, 0.5, di_scharr_dy, 0.5, 0) di_laplacian = cv.Laplacian(disnoy_img, cv.CV_64F) di_abs_lap64f = np.absolute(di_laplacian) di_scharr_std = di_scharr_img.std() di_lap_std = di_laplacian.std() di_abs_lap_std = di_abs_lap64f.std() beta = max(abs_lap_std, di_abs_lap_std) * 0.8 + max(lap_std, di_lap_std) * 0.5 + max(scharr_std, di_scharr_std) * 0.04 beta /= 3.0 t2 = time.time() print('T={}, beta={}, img_path={}'.format(t2 - t1, beta, os.path.basename(img_path))) show(img_path, gray_img, laplacian, abs_lap64f, scharr_img)
def scharr_demo(image): grad_x = cv2.Scharr(image, cv2.CV_32F, 1, 0) grad_y = cv2.Scharr(image, cv2.CV_32F, 0, 1) gradx = cv2.convertScaleAbs(grad_x) grady = cv2.convertScaleAbs(grad_y) gradxy = cv2.addWeighted(gradx, 0.5, grady, 0.5, 0) return gradxy
def canny(d_in, R, meth, edd): d = d_in if (R != 0): dt = np.fft.fft2(d) if meth == 'g': for i in range(sz): for j in range(sz): k2 = 1. * (i * i + j * j) / d.shape[0] dt[i, j] = dt[i, j] * np.exp(-k2 * R * R / 2) if meth == 'tp': for i in range(sz): for j in range(sz): k = np.sqrt(0.001 + i * i + j * j) / sz dt[i, j] = dt[i, j] * 3 * (np.sin(k * R) - k * R * np.cos(k * R)) / (k * R)**3 d = np.fft.ifft2(dt) d = abs(d) if edd == 'lap': d = cv2.Laplacian(d, cv2.CV_64F) if edd == 'sob': sobelx = cv2.Sobel(d, cv2.CV_64F, 1, 0, ksize=3) sobely = cv2.Sobel(d, cv2.CV_64F, 0, 1, ksize=3) d = np.sqrt(sobelx**2 + sobely**2) if edd == 'sch': scharrx = cv2.Scharr(d, cv2.CV_64F, 1, 0) scharry = cv2.Scharr(d, cv2.CV_64F, 0, 1) d = np.sqrt(scharrx**2 + scharry**2) return d
def calculateGradients(work_image,tgt_region): ''' This function uses Scharr operator to calculate derivatives/gradient in both x and y direction. Parameters: ----------- work_image: Image which is changed every iteration tgt_region: Boolean mask of pixels where True indicates object pixel ''' # convert to grayscale to calculate derivatives src_gray = cv2.cvtColor(work_image,cv2.COLOR_BGR2GRAY); # calculate x derivatives gradientX = cv2.Scharr(src_gray, cv2.CV_32F, 1, 0); # default parameter: scale shoule be 1 # calculate y derivatives gradientY = cv2.Scharr(src_gray, cv2.CV_32F, 0, 1); # set non source region gradient to be zero gradientY[tgt_region] = 0; gradientX[tgt_region] = 0; # normalise the gradients gradientX /= 255; gradientY /= 255; return (gradientY,gradientX);
def get_blurry_res(gray_img): """ by zj 获取图片的模糊程度, 目前只在定位环线夹上测试过 还有调整的空间 T = 0.05 :param img_path: :param disnoising: :return: blurry_res 模糊程度, 1 作为分界线, 越比 1 小越模糊, 越比 1 大越清晰 """ t1 = time.time() scharr_dx = cv2.Scharr(gray_img, cv2.CV_64F, 1, 0) scharr_dy = cv2.Scharr(gray_img, cv2.CV_64F, 0, 1) scharr_img = cv2.addWeighted(scharr_dx, 0.5, scharr_dy, 0.5, 0) laplacian = cv2.Laplacian(gray_img, cv2.CV_64F) abs_lap64f = np.absolute(laplacian) scharr_std = scharr_img.std() lap_std = laplacian.std() abs_lap_std = abs_lap64f.std() # disnoising disnoy_img = cv2.fastNlMeansDenoising(gray_img, h=3, templateWindowSize=7, searchWindowSize=21) # T=0.1 ~ 0.01 di_scharr_dx = cv2.Scharr(disnoy_img, cv2.CV_64F, 1, 0) di_scharr_dy = cv2.Scharr(disnoy_img, cv2.CV_64F, 0, 1) di_scharr_img = cv2.addWeighted(di_scharr_dx, 0.5, di_scharr_dy, 0.5, 0) di_laplacian = cv2.Laplacian(disnoy_img, cv2.CV_64F) di_abs_lap64f = np.absolute(di_laplacian) di_scharr_std = di_scharr_img.std() di_lap_std = di_laplacian.std() di_abs_lap_std = di_abs_lap64f.std() beta = max(abs_lap_std, di_abs_lap_std) * 0.8 + max(lap_std, di_lap_std) * 0.5 + max(scharr_std, di_scharr_std) * 0.04 beta = beta / 3.0 t2 = time.time() print('get_blurry_res T={:.4f}'.format(t2 - t1)) return beta
def images_gradient_laplacian(): """ laplacian算子 相当于二阶求导,对于边框更敏感,但是对于噪音点也是更敏感 :return: """ # 不同算子的差异比较 img = cv2.imread('{}/images/lena.jpg'.format(config.BASE_DIR, ), cv2.IMREAD_GRAYSCALE) sobelx = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=3) sobely = cv2.Sobel(img, cv2.CV_64F, 0, 1, ksize=3) sobelx = cv2.convertScaleAbs(sobelx) sobely = cv2.convertScaleAbs(sobely) sobelxy = cv2.addWeighted(sobelx, 0.5, sobely, 0.5, 0) scharrx = cv2.Scharr(img, cv2.CV_64F, 1, 0) scharry = cv2.Scharr(img, cv2.CV_64F, 0, 1) scharrx = cv2.convertScaleAbs(scharrx) scharry = cv2.convertScaleAbs(scharry) scharrxy = cv2.addWeighted(scharrx, 0.5, scharry, 0.5, 0) laplacian = cv2.Laplacian(img, cv2.CV_64F) laplacian = cv2.convertScaleAbs(laplacian) res = np.hstack((sobelxy, scharrxy, laplacian)) cv_show('res', res)
def doIt(image_path): o = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE) # 用 CV_64F 防止数字溢出 sobelX = cv2.Sobel(o, cv2.CV_64F, True, False) # 再转成 np.uint8 sobelX = cv2.convertScaleAbs(sobelX) sobelY = cv2.Sobel(o, cv2.CV_64F, False, True) sobelY = cv2.convertScaleAbs(sobelY) # 相加得到XY边界都显示的 sobelXY = cv2.addWeighted(sobelX, 0.5, sobelY, 0.5, 0) # 用 CV_64F 防止数字溢出 scharrX = cv2.Scharr(o, cv2.CV_64F, True, False) # 再转成 np.uint8 scharrX = cv2.convertScaleAbs(scharrX) scharrY = cv2.Scharr(o, cv2.CV_64F, False, True) scharrY = cv2.convertScaleAbs(scharrY) scharrXY = cv2.addWeighted(scharrX, 0.5, scharrY, 0.5, 0) laplacianImg = cv2.Laplacian(o, cv2.CV_64F) laplacianImg = cv2.convertScaleAbs(laplacianImg) cv2.imshow('original', o) cv2.imshow('sobelXY', sobelXY) cv2.imshow('scharrXY', scharrXY) cv2.imshow('laplacian', laplacianImg) cv2.waitKey() cv2.destroyAllWindows()
def detect_edge(channel): scharr_x = cv2.Scharr(channel, cv2.CV_16S, 1, 0) scharr_y = cv2.Scharr(channel, cv2.CV_16S, 0, 1) scharr = np.hypot(scharr_x, scharr_y) scharr[scharr > 255] = 255 return scharr
def computeNormal(psiHatP=None, filledImage=None, fillFront=None): assert filledImage is not None assert fillFront is not None assert psiHatP is not None ######################################### ## PLACE YOUR CODE BETWEEN THESE LINES ## ######################################### kw = 1 size = 2 * kw + 1 # Get target patch's pixels in fill front image front, _ = copyutils.getWindow(fillFront, psiHatP._coords, kw) # Center pixel's gradient Gx = cv.Scharr(src=front, ddepth=cv.CV_32F, dx=1, dy=0, borderType=cv.BORDER_REPLICATE)[kw][kw] Gy = cv.Scharr(src=front, ddepth=cv.CV_32F, dx=0, dy=1, borderType=cv.BORDER_REPLICATE)[kw][kw] # Change to unit vector d = np.sqrt(Gy**2 + Gx**2) if d != 0: Gx /= d Gy /= d # Change coordinations to kivy's display coordination Ny = Gy Nx = Gx ######################################### return Ny, Nx
def scharrAndLaplacianTest(): """ 图像梯度: Scharr算子: 比sobel算子更精细, Gx = [[-3, 0, 3], [-10, 0, 10], [-3, 0, 3]] Gy = [[-3, -10, -3], [0, 0, 0], [-3, -10, -3]] laplacian算子: 二阶导,对变化更明显, 但是对噪音敏感 G = [[0, 1, 0], [1, -4, 1], [0, 1, 0]] :return: """ # img = cv2.imread("./images/pie.png", cv2.IMREAD_GRAYSCALE) img = cv2.imread("./images/lena.jpg", cv2.IMREAD_GRAYSCALE) sobelX = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=3) sobelX = cv2.convertScaleAbs(sobelX) sobelY = cv2.Sobel(img, cv2.CV_64F, 0, 1, ksize=3) sobelY = cv2.convertScaleAbs(sobelY) sobelXY = cv2.addWeighted(sobelX, 0.5, sobelY, 0.5, 0) scharrX = cv2.Scharr(img, cv2.CV_64F, 1, 0) scharrY = cv2.Scharr(img, cv2.CV_64F, 0, 1) scharrX = cv2.convertScaleAbs(scharrX) scharrY = cv2.convertScaleAbs(scharrY) scharrXY = cv2.addWeighted(scharrX, 0.5, scharrY, 0.5, 0) laplacian = cv2.Laplacian(img, cv2.CV_64F) laplacian = cv2.convertScaleAbs(laplacian) res = np.hstack((sobelXY, scharrXY, laplacian)) cv_show(res)
def main(): path = "/home/g_r00t/PRIYANK/ex_images/" imgpath = path + "5.1.11.tiff" img = cv2.imread(imgpath, 1) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) edgesx = cv2.Scharr(img, -1, dx=1, dy=0, scale=1, delta=0, borderType=cv2.BORDER_DEFAULT) edgesy = cv2.Scharr(img, -1, dx=0, dy=1, scale=1, delta=0, borderType=cv2.BORDER_DEFAULT) edges = edgesx + edgesy output = [img, edgesx, edgesy, edges] titles = ['Original', 'dx=1 dy=0', 'dx=0 dy=1', 'Edges'] for i in range(4): plt.subplot(2, 2, i + 1) plt.imshow(output[i], cmap='gray') plt.title(titles[i]) plt.xticks([]) plt.yticks([]) plt.show()
def main(): imgpath = "C:\Shreyas\OpenCv\DIP_OpenCV\lena.png" img = cv2.imread(imgpath, 1) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) edgesx = cv2.Scharr(img, -1, dx=1, dy=0, scale=1, delta=0, borderType=cv2.BORDER_DEFAULT) edgesy = cv2.Scharr(img, -1, dx=0, dy=1, scale=1, delta=0, borderType=cv2.BORDER_DEFAULT) edges = edgesx + edgesy titles = ["Image", "dx=1 and dy=0", "dx=0 and dy=1", "Edges"] images = [img, edgesx, edgesy, edges] for i in range(4): plt.subplot(2, 2, 1 + i) plt.imshow(images[i], cmap="gray") plt.title(titles[i]) plt.xticks([]) plt.yticks([]) plt.show()
def harris_corner(img): src = cv2.GaussianBlur(img.astype(float), None, 1) Ix = cv2.Scharr(src, cv2.CV_64F, 1, 0) Iy = cv2.Scharr(src, cv2.CV_64F, 0, 1) Ixx = np.square(Ix) Iyy = np.square(Iy) Ixy = Ix * Iy Sxx = cv2.GaussianBlur(Ixx, None, 1.5) Syy = cv2.GaussianBlur(Iyy, None, 1.5) Sxy = cv2.GaussianBlur(Ixy, None, 1.5) R = (Sxx * Syy - Sxy * Sxy) / (Sxx + Syy + np.spacing(1)) ip = find_local_maxima(R) # remove boundary points boundary = 60 ip[:boundary, :] = 0 ip[-boundary:, :] = 0 ip[:, :boundary] = 0 ip[:, -boundary:] = 0 ip_loc = adaptive_non_maximal_suppression(ip) feature_points = [None] * ip_loc.shape[0] for i in range(0, len(feature_points)): feature_points[i] = FeaturePoint(x=ip_loc[i][1], y=ip_loc[i][0]) return feature_points
def gradient_operator(image, type=None): """ 梯度算子:sobel:一阶算子;laolacian:二阶算子 :param image: Original image input :param type: Operator`s type :return: Processed image """ image = cv2.imread(image) if type == 'sobel': sobelx = cv2.Sobel(image, cv2.CV_64F, 1, 0, ksize=3) sobely = cv2.Sobel(image, cv2.CV_64F, 0, 1, ksize=3) sobelx = cv2.convertScaleAbs( sobelx) # 白到黑是正数,黑到白就是负数了,所有的负数会被截断成0,所以要取绝对值 sobely = cv2.convertScaleAbs(sobely) image_result = cv2.addWeighted(sobelx, 0.5, sobely, 0.5, 0) elif type == 'scharr': scharrx = cv2.Scharr(image, cv2.CV_64F, 1, 0) scharry = cv2.Scharr(image, cv2.CV_64F, 0, 1) scharrx = cv2.convertScaleAbs(scharrx) scharry = cv2.convertScaleAbs(scharry) image_result = cv2.addWeighted(scharrx, 0.5, scharry, 0.5, 0) elif type == 'laplacian': laplacian = cv2.Laplacian(image, cv2.CV_64F) image_result = cv2.convertScaleAbs(laplacian) else: raise NameError("More operators are being added...") cv_show(type, image_result) return image_result
def get_image_gradient(self, img): gx = cv2.Scharr(img, cv2.CV_64F, 1, 0) gy = cv2.Scharr(img, cv2.CV_64F, 0, 1) #gx = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=3) #gy = cv2.Sobel(img,cv2.CV_64F,0,1,ksize=3) return gx, gy
def Call_OpenCV_Function_Scharr(src_img): dx = cv.Scharr(src_img, cv.CV_64F, 1, 0) dx = cv.convertScaleAbs(dx) dy = cv.Scharr(src_img, cv.CV_64F, 0, 1) dy = cv.convertScaleAbs(dy) dst = cv.addWeighted(dx, 0.5, dy, 0.5, 0) return dst