【问题标题】:Apply cv2.boundingRect on np.array在 np.array 上应用 cv2.boundingRect
【发布时间】:2016-11-08 23:47:46
【问题描述】:

如何将cv2.boundingRect 应用于np.array 的点数?
以下代码会产生错误。

points = np.array([[1, 2], [3, 4]], dtype=np.float32)
import cv2
cv2.boundingRect(points)

错误:

OpenCV Error: Unsupported format or combination of formats (The image/matrix format is not supported by the function) in cvBoundingRect, file /build/buildd/opencv-2.4.8+dfsg1/modules/imgproc/src/shapedescr.cpp, line 97

File "<ipython-input-23-42e84e11f1a7>", line 1, in <module>
  cv2.boundingRect(points)
error: /build/buildd/opencv-2.4.8+dfsg1/modules/imgproc/src/shapedescr.cpp:970: error: (-210) The image/matrix format is not supported by the function in function cvBoundingRect

【问题讨论】:

  • 我打算建议cv2.boundingRect(cv2.cv.fromarray(points)),但这似乎也不起作用。返回TypeError: points is not a numpy array, neither a scalar
  • 我试过你的代码,它给了我这个边界框没有错误(1、2、3、3),这似乎是真的。但是,我的 CV 版本是“3.1.0-dev”。

标签: python opencv


【解决方案1】:

OpenCV 2.x 版本的 Python 绑定使用的某些数据表示形式与 3.x 中的略有不同。

从现有的代码示例(例如,SO 上的this answer)中,我们可以看到我们可以使用cv2.findContours 返回的轮廓列表的 en 元素调用cv2.boundingRect。让我们看看它是什么样子的:

>>> a = cv2.copyMakeBorder(np.ones((3,3), np.uint8),1,1,1,1,0)
>>> b,c = cv2.findContours(a, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
>>> b[0]
array([[[1, 1]],

       [[1, 3]],

       [[3, 3]],

       [[3, 1]]])

我们可以看到轮廓中的每个点都表示为[[x, y]],并且我们有一个列表。

因此

import numpy as np
import cv2

point1 = [[1,2]]
point2 = [[3,4]]

points = np.array([point1, point2], np.float32)

print cv2.boundingRect(points)

我们得到输出

(1, 2, 3, 3)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-17
    • 2017-07-16
    • 1970-01-01
    • 1970-01-01
    • 2021-01-04
    • 1970-01-01
    相关资源
    最近更新 更多