1

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

有没有办法让一个窗口同时指示所有轮廓和形状的中心?

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

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

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)

链接到源

示例图像(将其重命名为shapes3.png)

4

1 回答 1

0

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)
于 2018-02-18T14:36:14.610 回答