首页 > 解决方案 > 如何使用opencv python 3计算图形图像中的行数

问题描述

我使用HoughLinesandHoughCircles来检测我的图形图像的线条和圆圈。我的代码已经可以很好地检测圆形了。但是,我不明白为什么我的代码没有正确检测到任何行。它检测到图片边框上的一些线条,但未检测到图形图片中的正确线条。这是我的带有输入和输出图像示例的代码。

输入图像

在此处输入图像描述

我的代码

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()

输出图像

在此处输入图像描述

标签: pythonopencv

解决方案


你可以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()

在此处输入图像描述


推荐阅读