import cv2
import numpy as np
# 根据OCR返回旋转角度对原图进行旋转,返回旋转后图片
def rotate_img(img, angle):
src_h, src_w = img.shape[:2]
M = cv2.getRotationMatrix2D(center=(src_w/2, src_h/2), angle=angle, scale=1.0)
abs_cos, abs_sin = abs(M[0,0]), abs(M[0,1])
dst_w = int(src_h * abs_sin + src_w * abs_cos)
dst_h = int(src_h * abs_cos + src_w * abs_sin)
M[0, 2] += (dst_w - src_w)/2
M[1, 2] += (dst_h - src_h)/2
img = cv2.warpAffine(img, M, (dst_w, dst_h), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT)
return img
# 根绝OCR返回旋转角度对原图坐标进行旋转,返回旋转后坐标(需原图尺寸)
# org_shape = [h, w]
# pt = [x, y]
def rotate_pt(org_shape, pt, angle):
src_h, src_w = org_shape[0], org_shape[1]
M = cv2.getRotationMatrix2D(center=(src_w/2, src_h/2), angle=angle, scale=1.0)
abs_cos, abs_sin = abs(M[0,0]), abs(M[0,1])
dst_w = int(src_h * abs_sin + src_w * abs_cos)
dst_h = int(src_h * abs_cos + src_w * abs_sin)
M[0, 2] += (dst_w - src_w)/2
M[1, 2] += (dst_h - src_h)/2
coordinate = np.array([pt], dtype=np.float32)
rotated_coordinate = cv2.transform(coordinate.reshape(-1,1,2), M)
return rotated_coordinate[0][0, :2]
# 根绝OCR返回旋转角度对旋转后坐标进行旋转,返回原图坐标(需原图尺寸)
# org_shape = [h, w]
# pt = [x, y]
def derotate_pt(org_shape, pt, angle):
src_h, src_w = org_shape[0], org_shape[1]
M = cv2.getRotationMatrix2D(center=(src_w/2, src_h/2), angle=angle, scale=1.0)
abs_cos, abs_sin = abs(M[0,0]), abs(M[0,1])
dst_w = int(src_h * abs_sin + src_w * abs_cos)
dst_h = int(src_h * abs_cos + src_w * abs_sin)
M[0, 2] += (dst_w - src_w)/2
M[1, 2] += (dst_h - src_h)/2
M_inv = np.linalg.inv(np.vstack([M, [0, 0, 1]]))[:2, :]
rotated_coordinate = np.array([pt], dtype=np.float32)
org_coordinate = cv2.transform(rotated_coordinate.reshape(-1,1,2), M_inv)
return org_coordinate[0][0, :2]
if __name__ == '__main__':
org_shape = [100, 200]
org_pt = [50, 25]
angle = 90
rot_pt = rotate_pt(org_shape, org_pt, angle)
print('org_shape:', org_shape, ', org_pt:', org_pt, ', angle:', angle)
print('==> rot_pt:', rot_pt)
derot_pt = derotate_pt(org_shape, rot_pt, angle)
print('==> derot_pt:', derot_pt)
Python图像旋转与坐标映射
于 2023-09-05 13:56:25 首次发布