梯度方向卷积 自己方法
我也忘记这是什么代码了,几年前的,今天翻到发布出来
import cv2 as cv import numpy as np import matplotlib.pyplot as plt import math img = cv.imread(r'C:\Users\51102\Desktop\tradition\1.jpg',0) img = cv.cvtColor(img, cv.COLOR_BGR2RGB) img = np.dot(img[..., :3], [0.299, 0.587, 0.114]) plt.subplot(331) plt.imshow(img,cmap='gray') plt.title('original_img') print('original.shape=',img.shape) # 构建梯度 gradient_x=np.array([[-1,0,1],[-2,0,2],[-1,0,1]]) gradient_y=np.array([[-1,-2,-1],[0,0,0],[1,2,1]]) plt.subplot(332) dx=cv.filter2D(img,ddepth=-1,kernel=gradient_x) print('dx.shape=',dx.shape) plt.imshow(dx,cmap='gray') plt.title('dx') plt.subplot(333) dy=cv.filter2D(img,-1,gradient_x) print('dy.shape=',dy.shape) plt.imshow(dy,cmap='gray') plt.title('dy') # 求方向 plt.subplot(334) magnitude=(np.multiply(dy,dy)+np.multiply(dx,dx)) plt.imshow(magnitude,cmap='gray') plt.title('magnitude') cita=cv.phase(dy,dx, angleInDegrees=True) # 求角度 # 生成高斯滤波器 """ 要生成一个 (2k+1)x(2k+1) 的高斯滤波器,滤波器的各个元素计算公式如下: H[i, j] = (1/(2*pi*sigma**2))*exp(-1/2*sigma**2((i-k-1)**2 + (j-k-1)**2)) """ sigma1 = sigma2 = 0.6 gau_sum = 0 gaussian = np.zeros([5, 5]) for i in range(5): for j in range(5): gaussian[i, j] = math.exp((-1/(2*sigma1*sigma2))*(np.square(i-2-1) + np.square(j-2-1)))/(2*math.pi*sigma1*sigma2) gau_sum = gau_sum + gaussian[i, j] gaussian = gaussian / gau_sum # 归一化处理 print('guss=',gaussian.shape) W, H = img.shape # 原始图片大小 灰度图 _,g=gaussian.shape new_gray = np.zeros([W-5, H-5]) new_magnitude = np.zeros([W-5, H-5]) for i in range(W-5): for j in range(H-5): ''' 滤波处理 我自创一种方法尝试,根据角度,来重新配置权重 我先降低梯度较大的幅度,对梯度方向进行抑制,其它方向进行加强 ''' guss=gaussian g_=int((g-1)/2) if 0<cita[i,j]<90 or 180<cita[i,j]<270 or -180<cita[i,j]<-90 or -360<cita[i,j]<-270: for k in range(g_): for kk in range(g_): guss[g_+1+k,g_+1+kk]=gaussian[g_+1+k,g_+1+kk]/4 guss[g_-1 - k, g_ - 1 - kk] = gaussian[g_ - 1 - k, g_ - 1 - kk] / 4 if 90 < cita[i, j] < 180 or 270 < cita[i, j] < 360 or -90 < cita[i, j] < 0 or -180 < cita[i, j] < -270: for k in range(g_): for kk in range(g_): guss[g_ + 1 + k, g_ - 1 - kk] = gaussian[g_ + 1 + k, g_ - 1 - kk] / 4 guss[g_ - 1 - k, g_ + 1 + kk] = gaussian[g_ - 1 - k, g_ + 1 + kk] / 4 new_gray[i, j] = np.sum(img[i:i+5, j:j+5] * guss) new_magnitude[i, j] = np.sum(magnitude[i:i + 5, j:j + 5] * guss) plt.subplot(335) plt.imshow(new_gray,cmap='gray') plt.title('new_gray') plt.subplot(336) plt.imshow(new_magnitude,cmap='gray') plt.title('new_magnitude') plt.show()
结果显示: