Python从现有列表创建新列表

时间:2015-07-26 21:12:47

标签: python list computer-vision contour

我想从现有的轮廓列表中创建一个四边形轮廓列表。我对编码很陌生,所以请忍受我用来证明目标的尝试代码。

#Get Contours from an Image
(contours,hierarchy) = cv2.findContours(image,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

#Work in progress
def ListQuads(contours,c=0):
    l = len(contours)  #Gets total number of contours
    while l > c:
        peri = cv2.arcLength(c, True)
        approx = cv2.approxPolyDP(c, 0.02 * peri, True)
        if len(approx) == 4:
            Quads[c] = approx
            c = c + 1
    return Quads

Quads = ListQuads(contours)

1 个答案:

答案 0 :(得分:2)

通常在Python中完成的方式是使用理解:

approximations = [cv2.approxPolyDP(c, 0.02 * cv2.arcLength(c, True), True)
                  for c in contours]
quads = [apx for apx in approximations if len(apx) == 4]

你甚至可以通过在aproximations理解中嵌套quads来在单个语句中得到这个,但这不会提高可读性。

只有在阅读变得容易的情况下,才能在Python中保存写入。

请注意,您也可以使用常规括号(...)而不是方括号[...]围绕它来使用生成器表达式而不是第一个表达式的理解。

在这种情况下,意思是计算approximations“懒惰”,如果原始列表很长,则节省内存。

相关问题