Python——基于OpenCV获取倾斜子图的一种方法
生活随笔
收集整理的這篇文章主要介紹了
Python——基于OpenCV获取倾斜子图的一种方法
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
解決方案?
#!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) / 2mat_rotation[1, 2] += (height_new - height) / 2img_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參考文章
?
總結(jié)
以上是生活随笔為你收集整理的Python——基于OpenCV获取倾斜子图的一种方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: TensorFlow——基于Keras子
- 下一篇: Python——web.py模块错误【U