
def Sobelfilter(m):
kernelx = [[1, 2, 1], [0, 0, 0], [-1, -2, -1]]
kernely = [[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]
# m2=scipy.ndimage.filters.convolve(m, kernelx, mode='nearest')
m2 = ndimage.filters.convolve(m, kernelx, mode='nearest')
m3 = ndimage.filters.convolve(m, kernely, mode='nearest')#numpy
#print('m2',m2,m3)
#需要加个abs
#return torch.from_numpy(m2+m3)
return (np.abs(m2+m3))
使用F.conv2d tensor
def sobel(batch_img):
#print(batch_img.shape)#torch.Size([1, 1, 5, 5])
ksize=3
C = 1
# kernelx = torch.tensor([[1.0, 2, 1], [0, 0, 0], [-1, -2, -1]])#.cuda()
# kernely = torch.tensor([[-1.0, 0, 1], [-2, 0, 2], [-1, 0, 1]])#.cuda()
kernelx = torch.tensor([[-1.0, -2, -1], [0, 0, 0], [ 1, 2, 1]]) # .cuda()
kernely = torch.tensor([[1.0, 0, -1], [2, 0, -2], [1, 0, -1]]) # .cuda()
kernely = kernely.view(1, 1, ksize, ksize).repeat(C, 1, 1, 1)#.cuda()
kernelx = kernelx.view(1, 1, ksize, ksize).repeat(C, 1, 1, 1)#.cuda()
#print(kernely.shape)
pad = (ksize - 1) // 2 # 保持卷积前后图像尺寸不变
#batch_img_pad=batch_img
#batch_img_pad = F.pad(batch_img, pad=[pad, pad, pad, pad], mode='reflect')
batch_img_pad = F.pad(batch_img, pad=[pad, pad, pad, pad], mode='replicate')#’constant‘, ‘reflect’ or ‘replicate’
#print('batch_img_pad',batch_img_pad)
weighted_pix = F.conv2d(batch_img_pad, weight=kernelx, bias=None,
stride=1, padding=0, groups=C)
weighted_piy = F.conv2d(batch_img_pad, weight=kernely, bias=None,
stride=1, padding=0, groups=C)
#print('weighted_pix',weighted_pix,weighted_piy)
#return weighted_pix+weighted_piy
return torch.abs(weighted_pix + weighted_piy)
test
def testsobel():
emeloss = EME()
lambdaR = 0.299
lambdaG = 0.587
lambdaB = 0.114
path=r'F:traindata_copyLOLeval_normal/normal00690.png'
img=cv2.imread(path,cv2.IMREAD_GRAYSCALE)
im=Sobelfilter(img)
img = np.expand_dims(img, axis=2)
source2 =torch.from_numpy(np.ascontiguousarray(img)).permute(2, 0, 1).float()#.div(255.)# util.uint2tensor3(img)
source2 = torch.unsqueeze(source2, dim=0)
img = source2 #* 255.0
print(img.shape)
#img=img.cuda()
im2=sobel(img)
print(img.shape,im2.shape)
im2 = im2.data.squeeze().float().cpu().numpy()
cv2.imwrite(r'F:traindata_copyLOL/normal00690.png',im)
cv2.imwrite(r'F:traindata_copyLOL/normal006902.png',im2)
r, g, b = readgray(path )
r=np.array(r)
g=np.array(g)
b=np.array(b)
cv2.imwrite(r'F:traindata_copyLOL/normal00690r.png', r)
cv2.imwrite(r'F:traindata_copyLOL/normal00690g.png', g)
cv2.imwrite(r'F:traindata_copyLOL/normal00690b.png', b)
lo1 = lambdaR * (r) + lambdaG * (g) + lambdaB * (b)
cv2.imwrite(r'F:traindata_copyLOL/normal00690rgb.png', lo1)
print(lo1.shape)
输入
Sobelfilter
R通道
G通道
B通道
RGB加权
sobel 灰度图
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)