Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a convolution function in Tensorflow to apply a Sobel filter?

Is there any convolution method in Tensorflow to apply a Sobel filter to an image img (tensor of type float32 and rank 2)?

sobel_x = tf.constant([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]], 'float32')
result = tf.convolution(img, sobel_x) # <== TO DO THIS

I've already seen tf.nn.conv2d but I can't see how to use it for this operation. Is there some way to use tf.nn.conv2d to solve my problem?

like image 488
axelbrz Avatar asked Feb 22 '16 22:02

axelbrz


2 Answers

Perhaps I'm missing a subtlety here, but it appears that you could apply a Sobel filter to an image using tf.expand_dims() and tf.nn.conv2d(), as follows:

sobel_x = tf.constant([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]], tf.float32)
sobel_x_filter = tf.reshape(sobel_x, [3, 3, 1, 1])
sobel_y_filter = tf.transpose(sobel_x_filter, [1, 0, 2, 3])

# Shape = height x width.
image = tf.placeholder(tf.float32, shape=[None, None])

# Shape = 1 x height x width x 1.
image_resized = tf.expand_dims(tf.expand_dims(image, 0), 3)

filtered_x = tf.nn.conv2d(image_resized, sobel_x_filter,
                          strides=[1, 1, 1, 1], padding='SAME')
filtered_y = tf.nn.conv2d(image_resized, sobel_y_filter,
                          strides=[1, 1, 1, 1], padding='SAME')
like image 187
mrry Avatar answered Oct 21 '22 02:10

mrry


Tensorflow 1.8 has added tf.image.sobel_edges() so that is the easiest and probably most robust way todo this now.

like image 35
Grant M Avatar answered Oct 21 '22 02:10

Grant M