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

2

5

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?

Streamline answered 22/2, 2016 at 22:35 Comment(0)
G
14

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')
Gymnast answered 23/2, 2016 at 6:0 Comment(5)
When finished I found it could be applied tf.squeeze(filtered_x). Thank you!Streamline
Can you explain a little bit more how does it work? How can I actually convolve a real image and show it?Marris
There is a typo in the second "sobel_x_filter" (soble_x_filter).Boatman
@Boatman Thanks for pointing that out! I've updated the code.Gymnast
your sobel_x filter is not correct. tf.constant([[1, 0, -1], [2, 0, -2], [1, 0, -1]], tf.float32) the most left must be swapped with the most right.Beaubeauchamp
S
3

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

Spermato answered 20/5, 2018 at 0:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.