解决方案
#!usr/bin/env python
# -*- coding:utf-8 _*-
"""
@version: 0.0.1
author: ShenTuZhiGang
@time: 2021/01/25 22:14
@file: imageutil.py
@function:
@modify:
"""
import cv2
from math import *
from PIL import Image
import numpy as np
def get_sub_image(image, box, adjust=False):
"""
获取倾斜矫正后的子图
:param image:
:param box:
:param adjust:
:return:
"""
height, width = image.shape[:2]
x_length = int((box[6] - box[0]) * 0.1)
y_length = int((box[7] - box[1]) * 0.2)
if adjust:
pt1 = (max(1, box[0] - x_length), max(1, box[1] - y_length))
pt2 = (box[2], box[3])
pt3 = (min(box[6] + x_length, width - 2),
min(height - 2, box[7] + y_length))
pt4 = (box[4], box[5])
else:
pt1 = (max(1, box[0]), max(1, box[1]))
pt2 = (box[2], box[3])
pt3 = (min(box[6], width - 2), min(height - 2, box[7]))
pt4 = (box[4], box[5])
# 图像倾斜角度
degree = degrees(atan2(pt2[1] - pt1[1], pt2[0] - pt1[0]))
# 倾斜矫正
height, width = image.shape[:2]
height_new = int(width * fabs(sin(radians(degree))) +
height * fabs(cos(radians(degree))))
width_new = int(height * fabs(sin(radians(degree))) +
width * fabs(cos(radians(degree))))
mat_rotation = cv2.getRotationMatrix2D((width / 2, height / 2), degree, 1)
mat_rotation[0, 2] += (width_new - width) / 2
mat_rotation[1, 2] += (height_new - height) / 2
img_rotation = cv2.warpAffine(
image, mat_rotation, (width_new, height_new), borderValue=(255, 255, 255))
pt1 = list(pt1)
pt3 = list(pt3)
[[pt1[0]], [pt1[1]]] = np.dot(mat_rotation,
np.array([[pt1[0]], [pt1[1]], [1]]))
[[pt3[0]], [pt3[1]]] = np.dot(mat_rotation,
np.array([[pt3[0]], [pt3[1]], [1]]))
y_dim, x_dim = img_rotation.shape[:2]
img_out = img_rotation[max(1, int(pt1[1])):min(y_dim - 1, int(pt3[1])),
max(1, int(pt1[0])):min(x_dim - 1, int(pt3[0]))]
# height,width=imgOut.shape[:2]
return img_out
参考文章