python - 如何使用opencv python 3计算图形图像中的行数
问题描述
我使用HoughLines
andHoughCircles
来检测我的图形图像的线条和圆圈。我的代码已经可以很好地检测圆形了。但是,我不明白为什么我的代码没有正确检测到任何行。它检测到图片边框上的一些线条,但未检测到图形图片中的正确线条。这是我的带有输入和输出图像示例的代码。
输入图像
我的代码
import numpy as np
import cv2 as cv
img = cv.imread('autoload.jpg')
output = img.copy()
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
blur = cv.medianBlur(gray, 5)
circles = cv.HoughCircles(blur, cv.HOUGH_GRADIENT, 1, 2, 100)
detected_circles = np.uint16(np.around(circles))
num_circle = 0
for (x, y ,r) in detected_circles[0, :]:
num_circle = num_circle + 1
cv.circle(output, (x, y), r, (0, 0, 255), 3)
edges = cv.Canny(gray,50,150,apertureSize = 3)
lines = cv.HoughLines(edges,1,np.pi/180,200)
num_line = 0
for line in lines:
num_line = num_line + 1
rho,theta = line[0]
a = np.cos(theta)
b = np.sin(theta)
x0 = a*rho
y0 = b*rho
x1 = int(x0 + 1000*(-b))
y1 = int(y0 + 1000*(a))
x2 = int(x0 - 1000*(-b))
y2 = int(y0 - 1000*(a))
cv.line(output,(x1,y1),(x2,y2),(255, 0, 0),3)
print("Number of Node:",num_circle)
print("Number of Edge",num_line)
output = cv.resize(output, (500, 750))
cv.imshow('output',output)
cv.waitKey(0)
cv.destroyAllWindows()
输出图像
解决方案
你可以cv.HoughLinesP
改用,我在下面粗略地做,它给出了重复的结果,例如你可以按邻近度过滤,或者找到比我使用的更好的参数。
import numpy as np
import cv2 as cv
img = cv.imread('image1.png')
output = img.copy()
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
edges = cv.Canny(gray, 50, 150, apertureSize=5)
lines = cv.HoughLinesP(edges, 1, np.pi/180, 100,
minLineLength=30, maxLineGap=2)
num_line = 0
for line in lines:
num_line = num_line + 1
x1,y1,x2,y2 = line[0]
cv.line(output,(x1,y1),(x2,y2),(255, 0, 0),3)
print("Number of Edge",num_line)
output = cv.resize(output, (500, 750))
cv.imshow('output',output)
cv.waitKey(0)
cv.destroyAllWindows()
推荐阅读
- python-3.x - BFS 查找源 S 和多个目标之间的所有最短路径
- javascript - 沿 SVG 路径输入时如何更改字体?
- azure-devops - 无法删除发布管道,因为它当前“部署在舞台上”错误
- c# - VS 函数,必须以字母开头,但接受字母后的数字
- php - 为什么 $Answer 永远不会等于 $Facit
- python - 如何在函数中返回多个图
- sql - 使用 NULL 参数调用雪花函数
- github-pages - Vuepress 站点在 github 页面上部署时无法正确加载
- php - 为什么当我在 mysql 中使用 whereRaw 和 where 时会得到不同的结果
- json - 如何为我的库存和 set_fact 中的每个主机选择一个嵌套的 json 值以供以后重用