计数齿轮(Python,OpenCV) [英] Count gear (Python, OpenCV)

查看:438
本文介绍了计数齿轮(Python,OpenCV)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于原型,我需要构建齿轮的3D模型.这有很多齿. 因此,我尝试使用OpenCV和Python来计算它们.我发现了(仅?)帖子,该帖子解释了如何在C ++中做到这一点.

For a prototype I need to build a 3d model of a gear. This have a "many" number of teeth. So I am trying to count them using OpenCV and Python. I found this (only?) post which explain how to do it in C++.

我正在按照步骤进行操作,现在这是我编写的代码.

I am following the steps and, for now this is the code I made.

import numpy as np
import cv2

img = cv2.imread('C:\\Users\\Link\\Desktop\\gear.png')

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)

kernel = np.ones((3, 3), np.uint8)

img_erosion = cv2.erode(thresh, kernel, iterations=1)

edges = cv2.Canny(img_erosion, 50, 150)

img_dilate = cv2.dilate(edges, kernel, iterations=1)

cv2.imshow('i', thresh)
cv2.waitKey(0)
cv2.imshow('i', img_erosion)
cv2.waitKey(0)
cv2.imshow('i', edges)
cv2.waitKey(0)
cv2.imshow('i', img_dilate)
cv2.waitKey(0)

阻止我前进的原因是:图像在某些时候变得一团糟.

What stopped me from go ahead is this: the image at some point became really a mess.

这是我正在使用的原稿:

This is the original on which I am working:

这是image_dilate

如您所见,底部的牙齿未正确显示,可能是由于原始图像中的阴影所致.我该如何摆脱呢?

As you can see, the teeth at the bottom is not displayed properly, maybe because of the shaddow in the original image. How can I get rid of this ?

推荐答案

因为您的源图片比帖子的链接更干净,因此您可以在最大区域上做大约轮廓,然后获得一半的点数,结果为 84 .

Because your source image is cleaner than the link your post, so you can do approx on the max-area-contour, then get half number of points, the result is 84.

示例代码:

#!/usr/bin/python3
# 2018.01.22 11:53:24 CST
import cv2
import myutils

## Read
img = cv2.imread("img13_2.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

## threshold and find contours
ret, threshed = cv2.threshold(gray, 50, 255, cv2.THRESH_BINARY_INV)
cnts= cv2.findContours(threshed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[-2]

## Find the max-area-contour
cnt = max(contours, key=cv2.contourArea)

## Approx the contour
arclen = cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt, 0.002*arclen, True)

## Draw and output the result
for pt in approx:
    cv2.circle(img, (pt[0][0],pt[0][1]), 3, (0,255,0), -1, cv2.LINE_AA)

msg = "Total: {}".format(len(approx)//2)
cv2.putText(img, msg, (20,40),cv2.FONT_HERSHEY_PLAIN, 2, (0,0,255), 2, cv2.LINE_AA)

## Display
cv2.imshow("res", img);cv2.waitKey()


结果:


Result:

这篇关于计数齿轮(Python,OpenCV)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆