python - Python OpenCV形状检测在白板上不起作用

标签 python python-3.x opencv image-processing

我们正在使用Python OpenCV形状检测。由于某种原因,它在下面的图片中不起作用。内部形状颜色与背景颜色相同时,是否需要更改参数才能运行?

它可以在网站示例中使用,因为黑色是背景色,并且形状是不同的颜色。

源代码来自这里:
https://www.pyimagesearch.com/2016/02/08/opencv-shape-detection/

当前不起作用:

enter image description here

运行程序控制台:

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

在教程中起作用:

enter image description here

最佳答案

在黑色背景上制作具有白色形状的二进制图像(反转和阈值)。

关于python - Python OpenCV形状检测在白板上不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61182231/

相关文章:

python - 我可以只将 Python .pyc 文件部署到 Google App Engine 吗?

python - 打开文件,读取它,处理,然后写回 - Python 中最短的方法

python - 如何解决这个错误: module 'gensim' has no attribute 'models'

python - 使用 Regex Python 计算一行中的三个字母首字母缩略词

Python 请求库 : use of json. 转储

android - 在 android opencv 中使用 findFundamentalMat 时出错,无法解决

python - 为什么我的列表的 .append() 将每个成员变量的值更改为新变量?

python - 如何在 Python 中获取类属性的定义顺序?

c++ - OpenCV 2.4.4 中的轮廓/连接组件

python-3.x - 去除图像圆形区域之外的颜色