- python
- pointxy:中心点;valuexy:目标点
def rotatePoint(angle, valuex, valuey, pointx, pointy):
valuex = np.array(valuex)
valuey = np.array(valuey)
sRotatex,sRotatey=0,0
if angle>0: # 绕pointx,pointy顺时针旋转
sRotatex = (valuex - pointx) * math.cos(angle) + (valuey - pointy) * math.sin(angle) + pointx
sRotatey = (valuey - pointy) * math.cos(angle) - (valuex - pointx) * math.sin(angle) + pointy
else: # 绕pointx,pointy逆时针旋转
angle=abs(angle)
sRotatex = (valuex - pointx) * math.cos(angle) - (valuey - pointy) * math.sin(angle) + pointx
sRotatey = (valuex - pointx) * math.sin(angle) + (valuey - pointy) * math.cos(angle) + pointy
程序使用
def run(
imgPath='./001.bmp',
outImgPath='./output.jpg',
angle=10.000102,
centerX=845.715454,
centerY = 1372.265747,
p0x=172.640686,
p0y=1732.116455,
p1x = 275.962372,
p1y = 1146.156006,
p2x = 877.679749,
p2y = 1252.256104,
p3x = 774.358032,
p3y = 1838.216553,
):
img = cv2.imread(imgPath)
height, width = img.shape[:2]
theta1 = angle # 顺时针旋转角度,单位为角度
x0, y0 = width // 2, height // 2 # 以图像中心作为旋转中心
MAR1 = cv2.getRotationMatrix2D((x0, y0), theta1, 1.0)
imgR1 = cv2.warpAffine(img, MAR1, (width, height)) # 旋转变换,默认为黑色填充
sCenterX,sCenterY=Srotate(math.radians(angle),centerX,centerY,x0,y0)
p0x, p0y = rotatePoint(math.radians(angle), p0x, p0y, x0, y0)
p1x, p1y = rotatePoint(math.radians(angle), p1x, p1y, x0, y0)
p2x, p2y = rotatePoint(math.radians(angle), p2x, p2y, x0, y0)
p3x, p3y = rotatePoint(math.radians(angle), p3x, p3y, x0, y0)
minX = min(p0x, p1x, p2x, p3x)
minY = min(p0y, p1y, p2y, p3y)
cropped_img = imgR1[int(minY):int(sCenterY), int(minX):int(sCenterX)]
cv2.imwrite(outImgPath, cropped_img)