Я изменяю этот код для работы с не квадратным изображением. Но что-то идет не так! Когда изображение квадратное, результат хороший! Спасибо за комментарий
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
# create toy image
height = 500
width = 600
square = np.zeros((1, height, width, 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.convert_to_tensor([[cos, -sin], [sin, cos]])
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, height, width, 3])
keypoints = tf.placeholder(tf.float32, [None, 3, 2])
angle = tf.random_uniform([]) # random angle, does not work
# rotate around the origin
image_r, keypoints_r = _rotate(image, tf.stack([keypoints[:, :, 0] / width, keypoints[:, :, 1] / height], axis=2), angle, 3)
keypoints_r = tf.stack([keypoints_r[:, :, 0] * width, keypoints_r[:, :, 1] * height], axis=2)
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')
Вот результат, полученный с не квадратным изображением:
