本文原理:先旋轉矩形到指定角度,然后提取矩形外輪廓,從而獲取旋轉后的矩形坐標點。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Author: tcy
# @Date: 2020-5-2 21:00:53
# @Version:V1.01
# @Last Modified by: tcy shanghai songjiang xiaokunshan
# @Last Modified time: 2020-5-7 21:21:10
import cv2,numpy as np
class Geometry(object):
def rotation_Scale(self,src, angle:'float',rotation_center:'(float,float)'=None,scale:'float'=1)->np.ndarray:#彩色:旋轉縮放
"""
:param src: ndarray
:param angle: float rotation angle
:param scale: float
:return: ndarray
retval = cv2.getRotationMatrix2D(center, angle, scale) // 圖像旋轉轉換矩陣
參數:
center旋轉中心點;
angle旋轉角度(正為逆時針)
scale變換尺度(縮放大小)
"""
rows, cols = src.shape[:2]
cx=rotation_center[0] if rotation_center else cols/2.0
cy=rotation_center[1] if rotation_center else rows/2.0
# cols - 1 and rows - 1 are the coordinate limits.
M = cv2.getRotationMatrix2D((cx, cy), angle, scale)
dst = cv2.warpAffine(src, M, (int(2*cx), int(2*cy)))
return dst
def circleRect(self,rect:"(pt1,pt2)",angle:float,w_image=480,h_image=640,rectcenter=True):
"""
:param rect: int,int,int,int 矩形左上角右下角坐標
:param angle: 旋轉角度 非弧度
:param w_image: 圖像寬度
:param h_image: 圖像高
:param rectcenter: bool or (int x,int y)指定繞指定點旋轉;True繞矩形中心旋轉;false繞圖像中心旋轉
:return: rect旋轉后矩陣坐標點;可能多于4點
"""
img=np.zeros((w_image,h_image),dtype=np.uint8)
cv2.rectangle(img,rect[0],rect[1],255,-1)
if len(rect)==4:
x1,y1,x2,y2=rect
else:
x1,y1=rect[0]
x2,y2=rect[1]
w_rect,h_rect=abs(x2-x1),abs(y2-y1)
# ret,binary=cv2.threshold(img,254,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
# cv2.line(img,(w_rect,h_rect),(w_rect,h_rect),125,5)
if rectcenter==False:
img_rotation=self.rotation_Scale(img,angle) #繞圖像中心點旋轉
elif rectcenter==True:
img_rotation=self.rotation_Scale(img,angle,(w_rect,h_rect))#繞矩形中心點旋轉
else:#參數設置不合理只能顯示部分圖像
img_rotation=self.rotation_Scale(img,angle,(rectcenter[0],rectcenter[1]))
contours,hierarchy=cv2.findContours(img_rotation,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
return contours[0].ravel()
def test_revolvePixs(self,image=None):
pt1=(100,100)
pt2=(300,300)
e1 = cv2.getTickCount() # 您的代碼執行
print('get point=',self.circleRect((pt1,pt2),45))
e2 = cv2.getTickCount()
t = (e2 - e1) / cv2.getTickFrequency() * 1000
print("runTime=", t, "ms") # 2.1672447196501228 ms
#===========================================================
if __name__=="__main__":
import os
#girl=os.getcwd()+'\\data\\girl.jpg'
#gray=os.getcwd()+'\\data\\fastener1.jpg'
a=Geometry()
a.test_revolvePixs()
https://blog.csdn.net/u013948010/article/details/78605043
python+opencv圖片旋轉矩形分割 這邊博文沒看明白,希望你能看懂。歡迎交流。希望分享更好的方法。