OCR倾斜文字截取矫正

import os
import cv2
import numpy as np
import math
from math import atan, fabs, sin, cos
def rotateImage(img,degree,pt1,pt2,pt3,pt4):
    height,width=img.shape[:2]
    heightNew = int(width * fabs(sin(degree)) + height * fabs(cos(degree)))
    widthNew = int(height * fabs(sin(degree)) + width * fabs(cos(degree)))
    matRotation=cv2.getRotationMatrix2D((width/2,height/2), math.degrees(degree), 1)
    matRotation[0, 2] += (widthNew - width) / 2
    matRotation[1, 2] += (heightNew - height) / 2
    imgRotation = cv2.warpAffine(img, matRotation, (widthNew, heightNew), borderValue=(255, 255, 255))
    pt1 = list(pt1)
    pt2 = list(pt2)
    pt3 = list(pt3)
    pt4 = list(pt4)
    [[pt1[0]], [pt1[1]]] = np.dot(matRotation, np.array([[pt1[0]], [pt1[1]], [1]]))
    [[pt2[0]], [pt2[1]]] = np.dot(matRotation, np.array([[pt2[0]], [pt2[1]], [1]]))
    [[pt3[0]], [pt3[1]]] = np.dot(matRotation, np.array([[pt3[0]], [pt3[1]], [1]]))
    [[pt4[0]], [pt4[1]]] = np.dot(matRotation, np.array([[pt4[0]], [pt4[1]], [1]]))  
    offset = 0 #边缘扩充
    #offset = int((pt3[1] - pt2[1])//3)    
    hmin = max(0, min(int(pt1[1]), int(pt4[1]))-offset//2)
    hmax = min(heightNew,max(int(pt3[1]),int(pt2[1]))+offset//2)
    wmin = max(0, min(int(pt3[0]),int(pt4[0]))-offset)
    wmax = min(widthNew, max(int(pt1[0]),int(pt2[0]))+offset)
    imgRot=imgRotation[hmin:hmax,wmin:wmax]
    return imgRot
    
if __name__ == '__main__':  
    imgpath='demo.jpg'
    imgdir,imgname=os.path.split(imgpath)
    img = cv2.imread(imgpath)
    pts = [(616, 898), (2069, 836), (2075, 986), (623, 1048)] #左上角,右上角,右下角,左下角坐标
    degree = math.atan((pts[1][1]-pts[0][1])/(pts[1][0]-pts[0][0]))
    print('degree',degree)
    cropedImg = rotateImage(img, degree, pts[0],pts[1],pts[2],pts[3])
    cv2.imwrite('crop_'+imgname, cropedImg)


原图:
在这里插入图片描述
offset=0,不扩充
在这里插入图片描述

扩充margin截图
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值