![](/img/trans.png)
[英]OpenCV Python: Draw minAreaRect ( RotatedRect not implemented)
[英]OpenCV's RotatedRect has no attribute 'size' in Python3. How to work around this?
我發現OpenCV 的 RotatedRect 類的.size.height
和.size.width
運算符在 Python 中不起作用,而在 C++ 中起作用。 讓我用一個簡化的代碼片段來詳細說明:
cap = cv2.VideoCapture('video1.mp4')
filter = RandomClass(20)
while(cap.isOpened()):
ret, frame = cap.read() # Read a frame
res = filter.classMain(frame) # Process the frame
if (res == 0):
print('Success') # If processing completed, print Success
cap.release()
其中類定義如下:
import cv2
import numpy as np
class RandomClass:
def __inti__(self):
self.set_skip_first(True)
def get_skip_first(self):
return self.skip_first
def set_skip_first(self, value):
self.skip_first = value
def classMain(self, frame):
if not get_skip_first():
self.expand_minRect(100) # expand the minRect by 100 pixels
# use the expanded rectangle for some other processing here
else:
self.set_skip_first(False)
# create a mask with cv2.inRange
contour = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE, offset=(0,0))[1]
# iterate over each contour and find the index of the largest contour
self.minRect = cv2.minAreaRect(np.array(self.contours[self.largest_contour_index]))
# execute some other processing here
return 0
def expand_minRect(self, value):
self.minRect.size.height = self.minRect.size.height + value
self.minRect.size.width = self.minRect.size.width + value
我收到的錯誤如下。 確切的行在上述代碼的 C++ 版本中工作得很好。
文件“文件名”,第 106 行,在 expand_minRect 中
self.minRect.size.height = self.minRect.size.height + 值
AttributeError: 'tuple' 對象沒有屬性 'size'
我嘗試了以下方法。 我期待第二印刷值(可變的width2
)為比所述第一印刷值(變量更大width1
通過) value
。
def expand_minRect(self, value):
_,(width1, height1),_ = self.minRect
print(width)
self.minRect[1][0] = self.minRect[1][0] + value
_,(width2,height2),_ = self.minRect
print(w)
但是它不起作用,因為self.minRect[1][0]
的變量類型是元組並且元組不能被修改。
文件“文件名”,第 111 行,在 expand_minRect 中
self.minRect 1 [0] = self.minRect 1 [0] + 值
類型錯誤:“元組”對象不支持項目分配
我做了一些研究,我找不到 RotatedRect 的 Python 文檔,但我找到了一個stackoverflow 的答案,指出
Python 仍然缺少 RotatedRect 類
因此,所有事情都放在一邊,假設 Python3 中的 RotatedRect 支持不完整,我該如何解決這個問題並擴展minRect
變量的寬度和高度?
根據本教程, minAreaRect
返回一個帶有((center_x,center_y),(width,height),angle)
的矩形。 因此,如果您修改expand_minRect
以使用正確的組件重新創建它,它應該可以工作。
def expand_minRect(self, value):
self.minRect = (self.minRect[0], # keep the center
(self.minRect[1][0] + value, self.minRect[1][1] + value), # update the size
self.minRect[2]) # keep the angle
注意:問題源於 OpenCV python 的面向對象實現比 OpenCV c++ 少。 它不返回允許按名稱訪問每個屬性的結構(如“ .size
”)。 您需要知道每個元素的元組順序和假設。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.