简体   繁体   中英

Displaying recognized shapes with Python opencv

I am still new to opencv, but I found a piece of code that identifies shapes contours in an image and indicates their center.The only issue is that the program would display one contour and one center, and the user has to close the window manually so the center of another shape, along with the first one, gets displayed.

Is there a way to have a single window indicating all contours and center of shapes at once?

This is quite problematic for me because I'm planning to replace the image with a camera stream later on. So, I would appreciate any additional suggestions for making this code more efficient.

Here's the code (the last 2 lines are the suspects):

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 to the source

范例图片 (rename it as shapes3.png)

The problem was fixed by displaying the image after the the for loop terminates

# 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM