在 np.array 上应用 cv2.boundingRect [英] Apply cv2.boundingRect on np.array

查看:55
本文介绍了在 np.array 上应用 cv2.boundingRect的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

points = np.array([[1, 2], [3, 4]], dtype=np.float32)导入 cv2cv2.boundingRect(点)

错误:

OpenCV 错误:在 cvBoundingRect,文件/build/buildd/opencv-2.4.8+dfsg1/modules/imgproc/src 中不支持格式或格式组合(函数不支持图像/矩阵格式)/shapeescr.cpp,第 97 行文件<ipython-input-23-42e84e11f1a7>",第1行,在<module>cv2.boundingRect(点)错误:/build/buildd/opencv-2.4.8+dfsg1/modules/imgproc/src/shapeescr.cpp:970:错误:(-210)函数cvBoundingRect中的函数不支持图像/矩阵格式

解决方案

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

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

<预><代码>>>>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)>>>乙[0]数组([[[1, 1]],[[1, 3]],[[3, 3]],[[3, 1]]])

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

因此

将 numpy 导入为 np导入 cv2点 1 = [[1,2]]点 2 = [[3,4]]点 = np.array([point1, point2], np.float32)打印 cv2.boundingRect(points)

我们得到输出

(1, 2, 3, 3)

How to apply cv2.boundingRect to a np.array of points ?
The following code produces an error.

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

Error:

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

解决方案

The Python bindings of the 2.x versions of OpenCV use slightly different representation of some data than the ones in 3.x.

From existing code samples (e.g. this answer on SO), we can see that we can call cv2.boundingRect with a en element of the list of contours returned by cv2.findContours. Let's have a look what that looks like:

>>> 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]]])

We can see that each point in the contour is represented as [[x, y]] and we have a list of those.

Hence

import numpy as np
import cv2

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

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

print cv2.boundingRect(points)

And we get the output

(1, 2, 3, 3)

这篇关于在 np.array 上应用 cv2.boundingRect的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆