如何在Python版OpenCV 3中创建Rect对象?解决引用找不到问题
Hey there! Let's break down the issue you're facing and fix it up.
First, the core problem: Python's OpenCV bindings don't have a cv2.Rect class—this is a key difference from C++ OpenCV, where cv::Rect is a built-in class. That's exactly why you're seeing that "Cannot find reference" error when trying to call cv2.Rect(p1, p2).
Since you want to create a rectangle object to use methods like area(), here are a few straightforward solutions:
1. Use basic tuple operations (quickest approach)
In Python OpenCV, rectangles are typically represented as a tuple (x, y, width, height). You can easily implement the functionality you need with simple functions:
# Define your rectangle using two diagonal points p1 = (10, 20) p2 = (40, 60) # Convert points to the standard (x, y, w, h) tuple x = min(p1[0], p2[0]) y = min(p1[1], p2[1]) w = abs(p1[0] - p2[0]) h = abs(p1[1] - p2[1]) rect = (x, y, w, h) # Calculate area def rect_area(rect): return rect[2] * rect[3] print(rect_area(rect)) # Output: 1200
2. Create a custom Rect class (object-oriented approach)
If you prefer a more class-based interface (similar to C++'s cv::Rect), you can build your own simple class with the methods you need:
class Rect: def __init__(self, p1, p2): # Initialize from two diagonal points self.x = min(p1[0], p2[0]) self.y = min(p1[1], p2[1]) self.width = abs(p1[0] - p2[0]) self.height = abs(p1[1] - p2[1]) def area(self): return self.width * self.height def contains(self, point): # Check if a (x, y) point is inside the rectangle px, py = point return self.x <= px <= self.x + self.width and self.y <= py <= self.y + self.height # Usage example my_rect = Rect((5, 5), (35, 45)) print(my_rect.area()) # Output: 1200 print(my_rect.contains((15, 25))) # Output: True
3. Work with OpenCV's built-in rectangle outputs
If you're getting rectangles from other OpenCV functions (like cv2.boundingRect() which returns a (x, y, w, h) tuple), you can either use it directly or pass its values to your custom Rect class:
# Example: Get bounding rectangle from a contour contour = ... # From cv2.findContours() bounding_rect = cv2.boundingRect(contour) # Convert to custom Rect class my_rect = Rect((bounding_rect[0], bounding_rect[1]), (bounding_rect[0]+bounding_rect[2], bounding_rect[1]+bounding_rect[3]))
To sum up: Python OpenCV favors lightweight data structures over complex classes, so you'll need to either use tuples with helper functions or roll your own class to replicate cv::Rect behavior.
内容的提问来源于stack exchange,提问作者Amit Keinan

