【问题标题】:find the bounding box of a white pixels set in opencv (python)找到在opencv(python)中设置的白色像素的边界框
【发布时间】:2020-09-25 11:37:34
【问题描述】:

我需要找到一团白色像素的最小面积矩形 ( cv2.minAreaRect() )。

我的图像中有多个白色物体,我想在它们周围画一个矩形。

我在 c++ 中找到了解决方案:

cv::cvtColor(img, gray, CV_BGR2GRAY);
std::vector<cv::Point> points;
cv::Mat_<uchar>::iterator it = gray.begin<uchar>();
cv::Mat_<uchar>::iterator end = gray.end<uchar>();
for (; it != end; ++it)
{
    if (*it) points.push_back(it.pos());
}
cv::RotatedRect box = cv::minAreaRect(cv::Mat(points));

这是我在 python 中的尝试:

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (5 ,5), 0)
retval, thresh = cv2.threshold(gray, 210, 255, cv2.THRESH_BINARY)
whitep = []
for y, row in enumerate(thresh):
    for x, px in enumerate(row):
        if px == 255:
            whitep.append((y, x))
box = cv2.minAreaRect(whitep)

但它不起作用:

box = cv2.minAreaRect(whitep)
TypeError: <unknown> is not a numpy array

我该怎么办? 谢谢

【问题讨论】:

  • 试试:box = cv2.minAreaRect(numpy.array(whitep))
  • 我已经试过了:错误:(-210)由于元素类型不合适,矩阵无法转换为点序列
  • 答案似乎在这里:stackoverflow.com/questions/8369547/…;试试:box = cv2.minAreaRect(numpy.array([whitep], dtype=numpy.int32))
  • 太棒了。我已将我的评论作为真实答案提供。

标签: python opencv


【解决方案1】:

minAreaRect 的 python 文档具有误导性。

用途:

box = cv2.minAreaRect(numpy.array([whitep], dtype=numpy.int32))

这会将一个形状为 (1,N,2) 的数组传递给 minAreaRect。

如果您使用默认整数类型为 numpy.int64 的系统,则需要指定 dtype。明确表达是最安全的。

另请参阅:Checking contour area in opencv using python

【讨论】:

    【解决方案2】:

    你也可以试试这个。在某些情况下 minAreaRect 确实失败了,但下面说明的方法总是有效。不过使用 PIL。

    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    gray = cv2.GaussianBlur(gray, (5 ,5), 0)
    retval,thresh = cv2.threshold(gray, 210, 255, cv2.THRESH_BINARY)
    mask=Image.fromarray(thresh)
    box = mask.getbbox()
    

    【讨论】:

      猜你喜欢
      • 2021-10-09
      • 2017-10-28
      • 2021-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-10
      • 1970-01-01
      • 2013-01-10
      相关资源
      最近更新 更多