gpt4 book ai didi

python - 使用python opencv检测刻度线

转载 作者:行者123 更新时间:2023-12-02 16:32:38 25 4
gpt4 key购买 nike

因此,我得到一个盒子的图像,并且在盒子内有许多刻度尺,就像尺子一样。如下图所示:
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
如您所见,不仅可以检测到刻度线(红色轮廓)和外部矩形(绿色轮廓),而且还可以将刻度线与外部矩形区分开。我还尝试获取刻度线拐角点的像素位置,以及在我的代码中看到的将拐角点存储到“角点= []”中的代码中
我也不确定是否将刻度线视为粗线或矩形。因此位置角点可以只是刻度线“line”的2个端点,也可以是刻度线“rectangle”的4个顶点。

最佳答案

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

关于python - 使用python opencv检测刻度线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62582543/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com