Python——基于OpenCV获取倾斜子图的一种方法

解决方案 

#!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

参考文章

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Starzkg

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值