Opencv Python如何检查齿轮的方向?

时间:2019-01-18 14:49:43

标签: python opencv

我正在检查齿轮的方向,无论是“向上”还是“向下”,“并将结果打印到屏幕上”。背景颜色始终为黑色。

此齿轮位于“上”位置:

https://imgur.com/a/DON8GJs

此齿轮位于“向下”位置:

https://imgur.com/a/4ODZQAt

我确实尝试对两个图像进行二值化和Canny边缘检测,但是我发现的只是这些算法的结果,仅此而已。我想知道如何检查齿轮的方向?您的帮助将不胜感激!!

1 个答案:

答案 0 :(得分:0)

向下的位置具有独特的形状,您可以使用shapematch来检测该形状的存在。
为此,您需要一个参考形状。我通过检测边缘来创建此图像,保存该图像并使用MS油漆仅保留所需的形状。
下面的代码向您展示了如何检测形状。它将齿轮的位置打印到终端,并绘制齿轮的形状(如果处于向下位置)。

Shapematch能够处理旋转,但是如果您想在某种自动化中使用它,则可能需要测试和调整一些设置。

结果: enter image description here

参考齿轮的图像: https://i.stack.imgur.com/s6E9C.jpg

代码:

import numpy as np 
import cv2

# load image of reference shape
image_reference = cv2.imread("ReferenceGear.jpg",0)
# threshold to remove artefacts
ret, img_ref = cv2.threshold(image_reference, 200, 255,0)
# detect contours in image
im, ref_cnts, hierarchy = cv2.findContours(img_ref, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# store the contour of the reference shape in a variable
ref_cnt = ref_cnts[0]


# load image 
image = cv2.imread("gear.png")
# detect edges in image
edges = cv2.Canny(image,50,50)
# detect contours of edges in image
im, contours, hierarchy = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# for each edge-contour in the image: try to match with te reference.
# if the value is very small, it is a good match. store the result in a variable
found = False
for cnt in contours:
    ret = cv2.matchShapes(cnt, ref_cnt,3,0.0)
    if ret < 0.001:
        cv2.drawContours(image, [cnt], 0, (255), 2)
        found = True
        break

if found:
    print("Gear is in down position")
else:
    print("Gear is in up position")

# show image and reference
cv2.imshow("image", image)
cv2.imshow("image_reference", image_reference)
# release resources
cv2.waitKey(0)
cv2.destroyAllWindows()