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?

mrry
  • 125,488
  • 26
  • 399
  • 400
axelbrz
  • 783
  • 1
  • 7
  • 16

2 Answers2

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')
mrry
  • 125,488
  • 26
  • 399
  • 400
  • When finished I found it could be applied tf.squeeze(filtered_x). Thank you! – axelbrz Feb 23 '16 at 18:34
  • 2
    Can you explain a little bit more how does it work? How can I actually convolve a real image and show it? – mavi Jan 25 '17 at 18:56
  • There is a typo in the second "sobel_x_filter" (soble_x_filter). – OliasailO Jun 20 '17 at 10:42
  • @OliasailO Thanks for pointing that out! I've updated the code. – mrry Jun 21 '17 at 15:39
  • 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. – j35t3r Apr 20 '18 at 11:29
3

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

Grant M
  • 648
  • 10
  • 21