使用openCV检测线的孔

使用openCV检测线的孔

本文介绍了使用openCV检测线的孔,末端和起点吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个Python脚本来检测线的孔,末端和起点.我认为openCV可以很好地实现这一目标.

I'm trying to create a Python script that detects holes, ends and beginnings of a line. I thought that openCV would be great to achieve this.

因此,例如,所有内容均以该图片开头:

So for example everything starts with this image:

最后我要实现的是:

因此,我首先将图像导入Python并进行灰度转换.现在,我想到了使用goodFeaturesToTrack()方法跟踪孔的想法.通常用于查找图像中的角.

So I began with importing the image into Python and converting it in grayscale. Now I came to the idea to track the holes by using the goodFeaturesToTrack() method. It's normally used to find corners in the image.

但是这种方法不能很好地工作,因为在此之后脚本知道了点,但是它不知道某个点是从孔开始还是是直线的起点或终点.另一个问题是,如果我使用其他图像,则此方法可以检测到的点不仅仅是线的孔,起点和终点.

However that didn't work so well because after that the script knows the points, but it doesn't know if a point is from a hole or if it's the beginning or end of the line. Another problem is that if I use another image this method detects more points than just the holes, beginnings and ends of the line.

这是我的完整代码,可以更好地理解我的问题:

Here is my full code to understand my problem a bit better:

import cv2
import numpy as np
import matplotlib.pyplot as plt

# lodes in img

img = cv2.imread('png1.png', cv2.IMREAD_COLOR)
img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)

corners = cv2.goodFeaturesToTrack(img_gray, 200, 0.05, 10)

for corner in corners:
    x, y = corner.ravel()
    cv2.circle(img, (x,y), 7, (255,255,0), -1)

cv2.imshow('img',img)

我不知道如何解决这个问题.

I have no idea to get around this problem.

推荐答案

我添加了一个func getLandmarks()函数,该函数返回所有整数.所以在这里,我假设如果半径为30像素的2个角都被计为一个孔

I added a func getLandmarks() it returns all the wholes. So here I assume that it will be counted as a hole if there are 2 corners in a radius of 30 pix

if abs(x1-x2)<=30 and abs(y1-y2)<=30:

此行定义范围.

import cv2
import numpy as np

def getLandmarks(corners):
    holes=[]
    for i in range(0,len(corners)):
        for j in range(i+1,len(corners)):
            x1,y1=corners[i].ravel()
            x2,y2=corners[j].ravel()
            if abs(x1-x2)<=30 and abs(y1-y2)<=30:
                holes.append((int((x1+x2)/2),int((y1+y2)/2)))
    return holes

# lodes in img

img = cv2.imread('img.png', cv2.IMREAD_COLOR)
img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)

corners = cv2.goodFeaturesToTrack(img_gray, 200, 0.05, 10)

holes=getLandmarks(corners)
print len(holes)
for corner in holes:
    cv2.circle(img, (corner), 7, (255,255,0), -1)

cv2.imshow('img',img)
cv2.waitKey(0)

输出

现在作为起点和终点您可以轻松地按X(如果路径沿左右方向)或Y(如果路径沿上下方向)对角进行排序,则最小值和最大值将是您的起点和终点.结束!

Now for the Start and end You can easily sort the corners in either X(if the Path is along left to right) or Y(If the path is along top to down) and the min and max will be your start and end!

这篇关于使用openCV检测线的孔,末端和起点吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 02:24