使用 Python opencv 显示识别的形状

Displaying recognized shapes with Python opencv

我还是 opencv 的新手,但我发现了一段代码,可以识别图像中的形状轮廓并指出它们 center.The 唯一的问题是程序会显示一个轮廓和一个中心,并且用户必须手动关闭 window 以便显示另一个形状的中心以及第一个形状。

有没有办法让一个 window 一次指示所有轮廓和形状中心?

这对我来说是一个很大的问题,因为我打算稍后用相机流替换图像。因此,对于使此代码更高效的任何其他建议,我将不胜感激。

这是代码(最后两行是嫌疑犯):

import argparse
import imutils
import cv2


image = cv2.imread("shapes3.png")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1]
# find contours in the thresholded image
cnts = cv2.findContours(thresh.copy(), cv2.RETR_TREE,
        cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if imutils.is_cv2() else cnts[1]

# loop over the contours
for c in cnts:
        print("1")
        # compute the center of the contour
        M = cv2.moments(c)
        cX = int(M["m10"] / M["m00"])
        cY = int(M["m01"] / M["m00"])

        # draw the contour and center of the shape on the image
        cv2.drawContours(image, [c], -1, (0, 255, 0), 2)
        cv2.circle(image, (cX, cY), 7, (229, 83, 0), -1)
        cv2.putText(image, "center", (cX - 20, cY - 20),
                cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 59, 174), 2)

        # show the image
        cv2.imshow("Image", image) #displaying processed image
        cv2.waitKey(0)

Link 到源

问题已通过在 for 循环终止后显示图像得到解决

# loop over the contours
for c in cnts:
        print("1")
        # compute the center of the contour
        M = cv2.moments(c)
        cX = int(M["m10"] / M["m00"])
        cY = int(M["m01"] / M["m00"])

        # draw the contour and center of the shape on the image
        cv2.drawContours(image, [c], -1, (0, 255, 0), 2)
        cv2.circle(image, (cX, cY), 7, (229, 83, 0), -1)
        cv2.putText(image, "center", (cX - 20, cY - 20),
                cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 59, 174), 2)
# show the image
cv2.imshow("Image", image) #displaying processed image
cv2.waitKey(0)