在我的代码片段中,我想构建一个Sobel滤波器,分别应用于图像(RGB)的每一层,最后将处理后的图像(仍然是RGB,但已被滤波)拼接在一起。
我不知道如何构建Sobel滤波器,其输入形状为[filter_depth, filter_height, filter_width, in_channels, out_channesl]
,在我这里是这样的:
sobel_x_filter = tf.reshape(sobel_x, [1, 3, 3, 3, 3])
整个代码看起来像这样:
回答:
你可以使用 tf.nn.depthwise_conv2d
:
sobel_x = tf.constant([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]], tf.float32)kernel = tf.tile(sobel_x[...,None],[1,1,3])[...,None]conv = tf.nn.depthwise_conv2d(image[None,...], kernel,strides=[1,1,1,1],padding='SAME')
使用 tf.nn.conv3d
:
im = tf.expand_dims(tf.transpose(image, [2, 0, 1]),0)sobel_x = tf.constant([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]], tf.float32)sobel_x_filter = tf.reshape(sobel_x, [1, 3, 3, 1, 1])conv = tf.transpose(tf.squeeze(tf.nn.conv3d(im[...,None], sobel_x_filter, strides=[1,1,1,1,1],padding='SAME')), [1,2,0])