【发布时间】:2021-05-05 00:25:32
【问题描述】:
我正在尝试将 python 代码转换为 C++,但我在下面的函数中遇到了问题 得到轮廓的旋转矩形: '''
def find_rot_rectangle_for_contour(contours):
# Find the rotated rectangles and ellipses for each contour
minRect = [None] * len(contours) # Initializing minRect
print('length of contour = ',len(contours))
count = None #count = 0
minLength = None # minLength = 0
tmpLength = 0 #tempLength = 0
for i, c in enumerate(contours): #index,c= contour
minRect[i] = cv.minAreaRect(c) # minRect is ((x,y), (w,h), angle), index(0, 1, 2)
minLength = min(minRect[i][1])
print('Minimum Length is',minLength)
if ((minLength > 500) and (minLength > tmpLength)):
count = i
tmpLength = minLength
return minRect, count
'''
我已将上述 python 代码转换为 C++,如下所示:
void find_rot_rectangle_for_contour(vector<vector<Point> > contour,vector<RotatedRect> minRect,unsigned int count)
{
unsigned int minLength = 0;
unsigned int tmpLength = 0;
RotatedRectangleOutput rotone;
vector<RotatedRect> minRectone(contour.size());
cout << "Contour size is" << contour.size() << endl;
//minRect[0] = RotatedRect(Point2f(100, 100), Size2f(100, 50), 30);
for (size_t i = 0; i < contour.size(); i++)
{
minRectone[i] = cv::minAreaRect(contour[i]);
minLength = MIN(minRectone[i].size.width,minRectone.size.height);
if ((minLength > 500) and (minLength > tmpLength))
{
count = i;
tmpLength = minLength;
}
}
minRect = minRectone;
}
我有几个问题:
a) for loop i python 代码有时会运行 46,38 次,具体取决于轮廓列表中轮廓的数量。 但在 C++ 代码中,contour.size() 返回 4000,因此与 python 代码不匹配。
b) c++ 代码在minLength = MIN(minRectone[i].size.width,minRectone.size.height); 中崩溃
在 python 代码中,我们得到 w,h for minRect 的行:minLength = min(minRect[i][1])
如何在 C++ 代码中进行类似的操作。
c) 在 python 代码中,轮廓是以下代码的输出:
contours_in, _ = cv.findContours(canny_in_output_dilated, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
在 C++ 代码中,轮廓是以下代码的输出:
findContours(canny_in_output_dilated, contours_in, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE);
是在 python 和 c++ 中返回轮廓的方式不同还是 我需要在 C++ 中将轮廓作为列表传递。在 python 中它被处理了吗?
【问题讨论】:
-
只需从所有点中获取 min x 和 y 以及 max x,y 然后你就得到了你的 bbox