首页 > 解决方案 > 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变量的宽度和高度?

标签: pythonpython-3.xopencvcomputer-visionimage-masking

解决方案


根据本教程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”)。您需要知道每个元素的元组顺序和假设。


推荐阅读