import os
import cv2
import numpy as np
import math
from math import atan, fabs, sin, cos
def rotateImage(img,degree,pt1,pt2,pt3,pt4):
height,width=img.shape[:2]
heightNew = int(width * fabs(sin(degree)) + height * fabs(cos(degree)))
widthNew = int(height * fabs(sin(degree)) + width * fabs(cos(degree)))
matRotation=cv2.getRotationMatrix2D((width/2,height/2), math.degrees(degree), 1)
matRotation[0, 2] += (widthNew - width) / 2
matRotation[1, 2] += (heightNew - height) / 2
imgRotation = cv2.warpAffine(img, matRotation, (widthNew, heightNew), borderValue=(255, 255, 255))
pt1 = list(pt1)
pt2 = list(pt2)
pt3 = list(pt3)
pt4 = list(pt4)
[[pt1[0]], [pt1[1]]] = np.dot(matRotation, np.array([[pt1[0]], [pt1[1]], [1]]))
[[pt2[0]], [pt2[1]]] = np.dot(matRotation, np.array([[pt2[0]], [pt2[1]], [1]]))
[[pt3[0]], [pt3[1]]] = np.dot(matRotation, np.array([[pt3[0]], [pt3[1]], [1]]))
[[pt4[0]], [pt4[1]]] = np.dot(matRotation, np.array([[pt4[0]], [pt4[1]], [1]]))
offset = 0 #边缘扩充
#offset = int((pt3[1] - pt2[1])//3)
hmin = max(0, min(int(pt1[1]), int(pt4[1]))-offset//2)
hmax = min(heightNew,max(int(pt3[1]),int(pt2[1]))+offset//2)
wmin = max(0, min(int(pt3[0]),int(pt4[0]))-offset)
wmax = min(widthNew, max(int(pt1[0]),int(pt2[0]))+offset)
imgRot=imgRotation[hmin:hmax,wmin:wmax]
return imgRot
if __name__ == '__main__':
imgpath='demo.jpg'
imgdir,imgname=os.path.split(imgpath)
img = cv2.imread(imgpath)
pts = [(616, 898), (2069, 836), (2075, 986), (623, 1048)] #左上角,右上角,右下角,左下角坐标
degree = math.atan((pts[1][1]-pts[0][1])/(pts[1][0]-pts[0][0]))
print('degree',degree)
cropedImg = rotateImage(img, degree, pts[0],pts[1],pts[2],pts[3])
cv2.imwrite('crop_'+imgname, cropedImg)
原图:
offset=0,不扩充
扩充margin截图