目前在做的检测过程中,有很多的矩形,需要旋转水平以后再截取出矩形区域,如下图所示。
看了很多方法,都是通过仿射变换方式,转正后截取
def crop_rect(img, rect):
# get the parameter of the small rectangle
center, size, angle = rect[0], rect[1], rect[2]
center, size = tuple(map(int, center)), tuple(map(int, size))
# get row and col num in img
height, width = img.shape[0], img.shape[1]
# calculate the rotation matrix
M = cv2.getRotationMatrix2D(center, angle, 1)
# rotate the original image
img_rot = cv2.warpAffine(img, M, (width, height))
# now rotated rectangle becomes vertical and we crop it
img_crop = cv2.getRectSubPix(img_rot, size, center)
return img_crop, img_rot
但是参考了 Cropping Rotated Rectangles from Image with OpenCV
这篇文章,主要就是运用了透视变换,非常巧妙
# -*- coding: utf-8 -*-
"""
File Name: rotation_v3
Description :
date: 2019/5/10
"""
import cv2
import numpy as np
import matplotlib.pylab as plt
import time
img=cv2.imread('3_75.jpg')
# img=img[14:-15,13:-14]
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
print("num of contours: {}".format(len(contours)))
rect = cv2.minAreaRect(contours[1]) #获取蓝色矩形的中心点、宽高、角度
'''
retc=((202.82777404785156, 94.020751953125),
(38.13406753540039, 276.02105712890625),
-75.0685806274414)
width = int(rect[1][0])
height = int(rect[1][1])
angle = rect[2]
print(angle)
if width < height: #计算角度,为后续做准备
angle = angle - 90
print(angle)
'''
if rect[-1] < -45 or rect[-1] > 45:
rect = (rect[0], (rect[1][1], rect[1][0]), rect[2] - 90)
angle = rect[2]
width = int(rect[1][0])
height = int(rect[1][1])
# if angle < -45:
# angle += 90.0
# #保证旋转为水平
# width,height = height,width
src_pts = cv2.boxPoints(rect)
# box = cv2.boxPoints(rect)
# box = np.int0(box)
# cv2.drawContours(img_box, [box], 0, (0,255,0), 2)
#
dst_pts = np.array([[0, height],
[0, 0],
[width, 0],
[width, height]], dtype="float32")
M = cv2.getPerspectiveTransform(src_pts, dst_pts)
warped = cv2.warpPerspective(img, M, (width, height))
if angle<=-90: #对-90度以上图片的竖直结果转正
warped = cv2.transpose(warped)
warped = cv2.flip(warped, 0) # 逆时针转90度,如果想顺时针,则0改为1
# warped=warped.transpose
cv2.imshow('wr1',warped)
cv2.waitKey(0)
仿射变换和透视变换的具体含义,可以参考知乎的这篇文章。
仿射变换是二维变换,就是在一个平面上,可以通过三个定点,随意的拉拽到想要的形状,但是不能拿起来,所以他的投影还是他拉拽的本身
透视变换是三维变换,就是可以拿起来,随意平行、竖直、翻转一定角度等,就是可以拉拽4个定点,所以它的投影会变成不规则的形状,更高级一点。