使用Python opencv显示已识别的形状

时间:2018-02-18 08:45:19

标签: python opencv shape-recognition

我还是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)

Link到来源

Example Image(将其重命名为shapes3.png)

1 个答案:

答案 0 :(得分: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)