【问题标题】:Detecting tick marks with python opencv使用 python opencv 检测刻度线
【发布时间】:2020-06-25 19:01:23
【问题描述】:

所以我得到了一个盒子的图像,盒子里有许多大小不一的刻度线,就像一把尺子。如下图:

This is the input picture

到目前为止,我的情况是,通过边缘检测,我只能将外部矩形检测为矩形,但不能检测矩形内的任何刻度线。代码如下:

import numpy as np
import cv2


image = cv2.imread('images\Ruler.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (3, 3), 0)
edges = cv2.Canny(blur, 50, 200)
cnts, hierarchy = cv2.findContours(edges, cv2.RETR_LIST, 
cv2.CHAIN_APPROX_SIMPLE)

corner_points = []


for index, cnt_points in enumerate(cnts):
    perimeter = cv2.arcLength(cnts[index], True)
    approx = cv2.approxPolyDP(cnts[index], 0.02 * perimeter, True)
    corner_points.append(approx)


    x, y, w, h = cv2.boundingRect(corner_points[index])
    cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)

print(corner_points)
cv2.imshow("Contour", image)
cv2.waitKey(0)
cv2.destroyAllWindows()

我希望生成的图像类似于下图所示:

Ideal result

正如您所见,不仅检测到刻度线(红色轮廓)和外部矩形(绿色轮廓),而且您还能够将刻度线与外部矩形区分开来。我也在尝试获取刻度线角点的像素位置,以及在我的代码中看到的我将角点存储到“角点 = []”

我也不确定刻度线是否被视为粗线或矩形。因此位置角点可以是刻度线“线”的两个端点,也可以是刻度线“矩形”的 4 个顶点。

【问题讨论】:

    标签: python opencv rectangles edge-detection


    【解决方案1】:
    import cv2
    
    img = cv2.imread('images/Ruler.png', cv2.IMREAD_GRAYSCALE)
    h, w, _ = img.shape
    
    bw = img > 128
    corner_points = []
    # if the pixel length of a line is higher than this threshold
    # add the start and end points to corner_points
    accepted_length = 10
    
    for i in range (0, h):
        start = -1  # the first True pixel in the row
        stop = -1  # the first False pixel after start
        for j in range (0, w):
            if bw(i,j) and start is -1:
                start = j
            if start is not -1 and not bw(i,j):
                stop = j
                # I added 50 here to avoid adding floor and ceil lines
                if stop - start > accepted_length and stop - start < 50:
                    corner_points.append([start end])
                continue
    

    【讨论】:

    • 我尝试运行您的代码,但似乎无法编译
    • @1acle 我没有测试它。这里的想法是将每条水平线添加到corner_points,除了顶部和底部。如果水平线的长度在某个阈值之间(此处为 10 和 50,可以更改),则意味着它不是垂直线的端点,也不是顶部或底部边缘。如果可以编译,请提出编辑请求以更正错误。如果这不是你想要的,但你想要一个通用的方法,我建议你使用Hough Line Transform
    猜你喜欢
    • 2019-08-28
    • 2019-04-28
    • 2013-03-24
    • 2016-08-21
    • 1970-01-01
    • 1970-01-01
    • 2014-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多