gpt4 book ai didi

python - TensorFlow:以随机角度旋转图像和点时的偏移

转载 作者:太空宇宙 更新时间:2023-11-04 02:12:03 24 4
gpt4 key购买 nike

我有一个图像和 3 个点。我想一起旋转图像和点。为此,我将图像旋转了某个角度 a 并将点旋转了相同的角度。当 a 固定为 python 标量(比如 pi/3)时,旋转效果很好(参见下图,蓝点位于黑色方 block 上)。

enter image description here

当使用 angle = tf.random_uniform([]) 随机选择角度时,旋转图像和旋转点之间存在偏移。

enter image description here

下面是重现此行为的完整代码。

我的问题是:如何解释并纠正这种行为?

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

# create toy image
square = np.zeros((1, 800, 800, 3))
square[:, 100:400, 100:400] = 1
square[:, 140:180, 140:180] = 0
square[:, 240:280, 240:280] = 0
square[:, 280:320, 280:320] = 0
kp = np.array([[160, 160], [260, 260], [300, 300]])
kp = np.expand_dims(kp, axis=0)

def _rotate(image, keypoints, angle, keypoints_num):
image = tf.contrib.image.rotate(image, angle)
cos, sin = tf.cos(angle), tf.sin(angle)
x0, y0 = .5, .5
rot_mat = tf.Variable([[cos, -sin], [sin, cos]], trainable=False)
keypoints -= (x0, y0)
keypoints = tf.reshape(keypoints, shape=[-1, 2])
keypoints = tf.matmul(keypoints, rot_mat)
keypoints = tf.reshape(keypoints, shape=[-1, keypoints_num, 2])
keypoints += (x0, y0)
return image, keypoints


image = tf.placeholder(tf.float32, [None, 800, 800, 3])
keypoints = tf.placeholder(tf.float32, [None, 3, 2])

angle = np.pi / 3 # fix angle, works fine
#angle = tf.random_uniform([]) # random angle, does not work
image_r, keypoints_r = _rotate(image, keypoints / 800, angle, 3)
keypoints_r *= 800

sess = tf.Session()
sess.run(tf.initialize_all_variables())

imr, kr = sess.run([image_r, keypoints_r], feed_dict={image: square, keypoints:kp})

# displaying output
plt.imshow(imr[0])
plt.scatter(*zip(*kr[0]))
plt.savefig('rotation.jpg')

最佳答案

问题出在这里:

rot_mat = tf.Variable([[cos, -sin], [sin, cos]], trainable=False)

因为rot_mat是一个变量,它的值只有在变量初始化的时候才会被设置,这里:

sess.run(tf.initialize_all_variables())

所以在那个时候 rot_mat 得到一些值(使用 cossin,这又取决于 angle,这是随机的)并且它不再改变。然后当你这样做时:

imr, kr = sess.run([image_r, keypoints_r], feed_dict={image: squares, keypoints:kps})

这是对 run 的不同调用,因此 tf.random_uniform 产生了一个新值,但是 rot_mat 仍然保持相同的值它被初始化了。由于图像旋转:

image = tf.contrib.image.rotate(image, angle)

关键点旋转:

keypoints = tf.matmul(keypoints, rot_mat)

旋转不匹配。最简单的解决方法是不为 rot_mat 使用变量:

rot_mat = [[cos, -sin], [sin, cos]]

这样,代码就可以正常工作了。如果你真的需要rot_mat作为一个变量,也是可以的,但是工作量有点大,这里好像不需要。如果您不喜欢 rot_mat 是一个列表并希望有一个适当的张量,您可以使用 tf.convert_to_tensor:

rot_mat = tf.convert_to_tensor([[cos, -sin], [sin, cos]])

关于python - TensorFlow:以随机角度旋转图像和点时的偏移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53524312/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com