报错代码
import sys
sys.path.append(r'D:\文档\Temp\WX-FIles\data')
# sys.path.append(r'D:\文档\Temp\WX-FIles\data')p11 = [125, 195]
p12 = [200, 275]
# and the corresponding two points on the second image are:p21 = [120, 190]
p22 = [200, 280]
# TODO: write your own code to calculate the rotation and scaling parameter
import numpy as np
import cv2
import matplotlib.pyplot as pltA1 = np.array(p11)
A2 = np.array(p12)
B1 = np.array(p21)
B2 = np.array(p22)
#计算平移向量
t_vector = B1 - A1
# 计算平移后的B2
t_B2 = B2 + t_vector
# 计算旋转角度
rotation = np.arctan2(t_B2[1] - B1[1], t_B2[0] - B1[0]) - np.arctan2(A2[1] - A1[1], A2[0] - A1[0])
print("旋转角度:", rotation, end=' ')
# 计算放缩比例
scale = np.linalg.norm(A2 - A1) / np.linalg.norm(t_B2 - B1)
print("放缩比例:", scale)# TODO: apply the rotation and scaling on the image
# 计算旋转矩阵
# print('np.degrees(rotation) = ' , np.degrees(rotation))
# print('tuple(A1) = ' ,tuple(A1))
r_matrix = cv2.getRotationMatrix2D(tuple(A1), np.degrees(rotation), scale=scale)
# (c1,c2)=tuple(A1)
# print('c1=',c1)
# print('c2=',c2)# r_matrix = cv2.getRotationMatrix2D((int(c1),int(c2)), np.degrees(rotation), scale=scale)
print("旋转矩阵:", r_matrix)
image = plt.imread(r'.\data\dog.bmp')
# 旋转放缩图像
t_image = cv2.warpAffine(image, r_matrix, (image.shape[1], image.shape[0]), borderMode=cv2.BORDER_REPLICATE)
# show
plt.figure(figsize=(12, 10))
plt.subplot(1, 2, 1)
plt.imshow(image)
plt.subplot(1, 2, 2)
plt.imshow(t_image)
plt.show()
后面分析
(c1,c2)=tuple(A1)
print('c1=',type(c1))
print('c2=',type(c2))
得到了c1和c2嘚类型为numpy.int32,其中函数cv2.getRotationMatrix2D嘚第一个参数需要传入int类型整数而不是numpy.int32类型嘚数字,因此报错.
最后解决办法是unpack 元组得到c1,c2,最后使用int(c1),int(c2),然后(int(c1),int(c2))合并为整数元组的形式.