Как повернуть координаты (x, y) изображения на определенный угол - PullRequest
1 голос
/ 04 октября 2019

Чтобы лучше понять, пожалуйста, воспроизведите код в Jupyternotebook:

У меня есть два файла: img.jpg и img.txt. Img.jpg - это изображение, а img.txt - это ориентиры на лице ... Если вы нанесете их оба, это будет выглядеть так:

enter image description here

Я повернул изображение на 24,5 градуса .... но как мне также повернуть координаты?

enter image description here

import cv2
img = cv2.imread('img.jpg')
plt.imshow(img)
plt.show()


# In[130]:


landmarks = []
with open('img.txt') as f:
    for line in f:
        landmarks.extend([float(number) for number in line.split()])
landmarks.pop(0) #Remove first line. 
#Store all points inside the variable. 
landmarkPoints = [] #Store the points in this
for j in range(int(len(landmarks))):
    if j%2 == 1:
        continue
    landmarkPoints.append([int(landmarks[j]),int(landmarks[j+1])])


# In[ ]:

def rotate_bound(image, angle):
# grab the dimensions of the image and then determine the
# center
(h, w) = image.shape[:2]
(cX, cY) = (w // 2, h // 2)

# grab the rotation matrix (applying the negative of the
# angle to rotate clockwise), then grab the sine and cosine
# (i.e., the rotation components of the matrix)
M = cv2.getRotationMatrix2D((cX, cY), -angle, 1.0)
cos = np.abs(M[0, 0])
sin = np.abs(M[0, 1])

# compute the new bounding dimensions of the image
nW = int((h * sin) + (w * cos))
nH = int((h * cos) + (w * sin))

# adjust the rotation matrix to take into account translation
M[0, 2] += (nW / 2) - cX
M[1, 2] += (nH / 2) - cY

# perform the actual rotation and return the image
return cv2.warpAffine(image, M, (nW, nH)) 



# In[131]:


imgcopy = img.copy()
for i in range(len(landmarkPoints)):
    cv2.circle(imgcopy, (landmarkPoints[i][0], landmarkPoints[i][1]), 5, (0, 255, 0), -1)
plt.imshow(imgcopy)
plt.show()
landmarkPoints


# In[146]:


print(img.shape)
print(rotatedImage.shape)


# In[153]:


face_angle = 24.5
rotatedImage = rotate_bound(img, -face_angle)
for i in range(len(landmarkPoints)):
    x,y = (landmarkPoints[i][0], landmarkPoints[i][1])
    cv2.circle(rotatedImage, (int(x),int(y)), 5, (0, 255, 0), -1)
plt.imshow(rotatedImage)
plt.show()

Пожалуйста, скачайте img.jpg и img.txt для воспроизведения: https://drive.google.com/file/d/1FhQUFvoKi3t7TrIepx2Es0mBGAfT755w/view?usp=sharing

Я попробовал эту функцию, но ось Y неверна

def rotatePoint(angle, pt):
    a = np.radians(angle)
    cosa = np.cos(a)
    sina = np.sin(a)
    return pt[0]*cosa - pt[1]*sina, pt[0] * sina + pt[1] * cosa

Редактировать: вышеупомянутая функция дает мне этот результат:

enter image description here

1 Ответ

0 голосов
/ 04 октября 2019

Когда вы пытаетесь делать такие вещи, очень важно выбрать правильную систему координат. В вашем случае вы должны поместить исходную точку (0,0) в центр изображения.

Как только вы примените вращение к координатам с исходной точкой в ​​центре, точки лица будут правильно выровнены поновое изображение.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...