python - OpenCV 的 RotatedRect 在 Python3 中没有属性“大小”。如何解决这个问题?
问题描述
我发现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
变量的宽度和高度?
解决方案
根据本教程,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
”)。您需要知道每个元素的元组顺序和假设。
推荐阅读
- javascript - 我如何通过 JavaScript 和 jQuery 在 word 文档的标题中插入图像
- php - PHP 5 到 PHP 7 的迁移
- javascript - 在 redux 中获取 api 的最佳方法是什么?
- javascript - 为什么我的 React Text 组件没有显示文本?(反应 360)
- odoo-10 - 如何在odoo10中使库存经理的字段不可见
- c++ - 我们可以将阈值应用于颜色空间模型的单个组件,如 RGB 和 LAB 吗?
- google-bigquery - BigQuery:在自动化作业中询问的凭据
- perl - ne nice editor syntax highlighting - Perl 变量未突出显示
- getuikit - UIKit 2 (getuikit) - 灯箱 - 触控设备上的上一个/下一个
- sql-server - 微软sql server managemenet studio 忙于内部操作