我发现OpenCV 的 RotatedRect 类.size.height
的and.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:“元组”对象没有属性“大小”
我尝试了以下。我期望第二个打印值(变量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] + 值
TypeError:“元组”对象不支持项目分配
我做了一些研究,我找不到 RotatedRect 的 Python 文档,但我找到了一个stackoverflow 答案,说明
Python 仍然缺少 RotatedRect 类
所以所有的事情,假设 Python3 中的 RotatedRect 支持不完整,我该如何解决这个问题并扩展我的minRect
变量的宽度和高度?