Python图像旋转与坐标映射

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值