【发布时间】: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)) -
太棒了。我已将我的评论作为真实答案提供。