我正在编写一个简单的辅助函数,它遍历所有已找到的轮廓并对它们执行某些操作。我的问题是,有没有办法对这个for循环进行矢量化,以使代码更有效
def TL(contours):
k = 0
for j, cnt in enumerate(contours):
k =+ 1
# x,y,w,h = cv2.boundingRect(cnt)
area = cv2.contourArea(cnt)
# r = w/h
# if r <= 1.2*2.142 and r >= 0.8*2.142:
approx = cv2.approxPolyDP(cnt, 0.01*cv2.arcLength(cnt, True), True)
if area > 50 and cv2.isContourConvex(cnt) == False and len(approx)<=15 and len(approx)>=8: # and len(approx)>=8
# cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2)
(xc,yc),radius = cv2.minEnclosingCircle(cnt)
# cv2.circle(frame,(int(xc),int(yc)),int(radius*0.9),(0,255,0),2)
# TARGET = (xc,yc-radius-1)
# nearest = find_nearest_white(TARGET)
h = int(radius*4)
w = int(h*2.25)
x = int(xc-(1/3)*w)
y = int(yc-h/2)
if w*h <= 4000:
cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2)
continue
return frame
你有一组轮廓,代码中最慢的部分(根据你的评论)是cv2.minEnclosingCircle()
。
我可以看到两种主要方法:
cv2.minEnclosingCircle()
的实现,看看你是否可以建立一个更快的(为你的输入)。这里提到了一些算法:How can I find the minimal circle include some given points?cv2.minEnclosingCircle()
调用可以并行(可能提前)完成,因为它们都是独立的。