分类: Python/Ruby
2017-10-09 14:21:42
def Rotate(pimg): angle = 45 w,h = pimg.size centerx = w / 2 centery = h / 2 w = w - 1 h = h - 1 x = 0 y = 0 x1 = x y1 = y x1t= int((x1 - centerx)*math.cos(angle) - (y1 - centery)*math.sin(angle) + centerx) y1t= int((x1 - centerx)*math.sin(angle) + (y1 - centery)*math.cos(angle) + centery) x2 = w y2 = 0 x2t= int((x2 - centerx)*math.cos(angle) - (y2 - centery)*math.sin(angle) + centerx) y2t= int((x2 - centerx)*math.sin(angle) + (y2 - centery)*math.cos(angle) + centery) x3 = 0 y3 = h x3t= int((x3 - centerx)*math.cos(angle) - (y3 - centery)*math.sin(angle) + centerx) y3t= int((x3 - centerx)*math.sin(angle) + (y3 - centery)*math.cos(angle) + centery) x4 = w y4 = h x4t= int((x4 - centerx)*math.cos(angle) - (y4 - centery)*math.sin(angle) + centerx) y4t= int((x4 - centerx)*math.sin(angle) + (y4 - centery)*math.cos(angle) + centery) minx = min(x1t, x2t, x3t, x4t) maxw = max(x1t, x2t, x3t, x4t) nw = maxw - (minx) miny = min(y1t, y2t, y3t, y4t) maxh = max(y1t, y2t, y3t, y4t) nh = maxh - (miny) pts1 = np.float32([[x1, y1], [x2, y2], [x3, y3], [x4, y4]]) pts2 = np.float32( [[x1t - (minx), y1t - (miny)], [x2t - (minx), y2t - (miny)], [x3t - (minx), y3t - (miny)], [x4t - (minx), y4t - (miny)]]) M_rotate = cv2.getPerspectiveTransform(pts1, pts2) array = np.array(pimg) dst = cv2.warpPerspective(array, M_rotate, (nw, nh), flags=cv.CV_WARP_FILL_OUTLIERS+cv.CV_INTER_AREA) img = Image.fromarray(dst).convert("RGBA") return img图片在(centerx,centery)旋转angle度后原图片的(x,y)点在新图上的(x1,y1)的计算:
x1=int((x1 - centerx)*math.cos(angle) - (y1 - centery)*math.sin(angle) + centerx) + (offsetX) y1=int((x1 - centerx)*math.sin(angle) + (y1 - centery)*math.cos(angle) + centery) + (offsetY)
M = cv2.getPerspectiveTransform(pts1, pts2) dst = cv2.warpPerspective(array, M, (nw, nh), flags=cv.CV_WARP_FILL_OUTLIERS+cv.CV_INTER_AREA)原图(x,y)透视变换后在新图上的坐标:
a = np.array([[x, y]], dtype='float32') a = np.array([a]) dst = cv2.perspectiveTransform(a, M) xy = dst[0][0].astype('int')