简体   繁体   中英

Python OpenCV Shape Detection Not Working on Whiteboard

We are using Python OpenCV Shape Detection. For some reason its not working in picture below. Are there parameters which need to be changed to run, where inner shape colors are the Same as background colors?

It works in website example, since black is the background color, and the shapes are different colors.

Source code from here: https://www.pyimagesearch.com/2016/02/08/opencv-shape-detection/

Currently Not working:

在此处输入图像描述

Run Program Console:

$ python detect_shapes.py --image imagetest.png

shapedetector.py

# if the shape is a triangle, it will have 3 vertices
if len(approx) == 3:
    shape = "triangle"
# if the shape has 4 vertices, it is either a square or
# a rectangle
elif len(approx) == 4:
    # compute the bounding box of the contour and use the
    # bounding box to compute the aspect ratio
    (x, y, w, h) = cv2.boundingRect(approx)
    ar = w / float(h)
    # a square will have an aspect ratio that is approximately
    # equal to one, otherwise, the shape is a rectangle
    shape = "square" if ar >= 0.95 and ar <= 1.05 else "rectangle"
# if the shape is a pentagon, it will have 5 vertices
elif len(approx) == 5:
    shape = "pentagon"
# otherwise, we assume the shape is a circle
else:
    shape = "circle"
# return the name of the shape
return shape

detect_shape.py

# loop over the contours
for c in cnts:
    # compute the center of the contour, then detect the name of the
    # shape using only the contour
    M = cv2.moments(c)
    cX = int((M["m10"] / M["m00"]) * ratio)
    cY = int((M["m01"] / M["m00"]) * ratio)
    shape = sd.detect(c)
    # multiply the contour (x, y)-coordinates by the resize ratio,
    # then draw the contours and the name of the shape on the image
    c = c.astype("float")
    c *= ratio
    c = c.astype("int")
    cv2.drawContours(image, [c], -1, (0, 255, 0), 2)
    cv2.putText(image, shape, (cX, cY), cv2.FONT_HERSHEY_SIMPLEX,
        0.5, (255, 255, 255), 2)
    # show the output image
    cv2.imshow("Image", image)
    cv2.waitKey(0)

Works here in tutorial:

在此处输入图像描述

Make binary image with white shapes on black background (invert and threshold).

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