我按照这个opencv指南按大小对第一张图像中的轮廓进行排序。
我计算了边缘图(结果是中间的图像):
# load the image and initialize the accumulated edge image
image = cv2.imread("legos.png")
accumEdged = np.zeros(image.shape[:2], dtype="uint8")
# loop over the blue, green, and red channels, respectively
for chan in cv2.split(image):
# blur the channel, extract edges from it, and accumulate the set
# of edges for the image
chan = cv2.medianBlur(chan, 11)
edged = cv2.Canny(chan, 50, 200)
accumEdged = cv2.bitwise_or(accumEdged, edged)
# show the accumulated edge map
cv2.imwrite("images/Edge_Map.png", accumEdged)
然后我计算并绘制了一些轮廓:
def draw_contour(image, c, color):
# compute the center of the contour area
M = cv2.moments(c)
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
# draw the countour and its area on the image
cv2.drawContours(image, [c], -1, color, 2)
cv2.putText(image, str(cv2.contourArea(c)), (cX - 10, cY - 15), cv2.FONT_HERSHEY_SIMPLEX, 0.65, color,2)
# find contours in the accumulated image
cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
sorted_cnts = sorted(cnts, key=cv2.contourArea, reverse=True)
draw_contour(image, sorted_cnts[0], (0, 0, 0)) # forth brick
draw_contour(image, sorted_cnts[4], (80, 0, 80)) # small circle
draw_contour(image, sorted_cnts[6], (255, 255, 255)) # third brick
问题是轮廓没有排序(按照我的想法)。我包括了第一、第五和第七个轮廓及其面积。第五个(229 区)明显小于第七个(130 区)。
我想知道 cv2.contourArea 在这种情况下会做什么。
使用
def polygon_area(coords):
n = len(coords)
area = 0
for i in range(n):
j = (i + 1) % n
area += coords[i][0] * coords[j][1]
area -= coords[j][0] * coords[i][1]
area = abs(area) / 2.0
return area