【问题标题】:Multiple Horizontal & Vertical Lines are not showing未显示多条水平和垂直线
【发布时间】:2019-05-03 15:13:24
【问题描述】:

在这里,我试图使用 opencv、霍夫变换来找到水的高度。该程序由精明边缘检测、背景减除、霍夫变换和高度估计组成。然后使用它绘制图形的高度。但这只会检测垂直线。未显示多条水平和垂直线。代码有问题吗?

程序的输出:

from imutils.perspective import four_point_transform
from imutils import paths
import numpy as np
import imutils 
import argparse
import cv2
import random
import math
import matplotlib.pyplot as plt

scaling_factorx = 0.8
scaling_factory = 0.8

cap = cv2.VideoCapture(0)
fgbg = cv2.createBackgroundSubtractorMOG2()
cap.set(3,640)
cap.set(4,480)
count = 0
height = []

while(1):

    ret, frame = cap.read()

    if frame is None:
        break
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    edges = cv2.Canny(gray, 1, 100)
    lines = cv2.HoughLinesP(edges, rho = 1,theta = 2*np.pi/180,threshold = 10,minLineLength = 100,maxLineGap = 10);
    if lines is not None:
        for line in lines[0]:
            dot1 = (line[0],line[1])
            dot2 = (line[2],line[3])
            cv2.line(frame, dot1, dot2, (255,0,0), 3)
            length = line[1] - line[3]
            print(length)
            height.append(length)

    cv2.imshow("output", frame)

    frame = cv2.resize(frame, None, fx = scaling_factorx, fy = scaling_factory, interpolation = cv2.INTER_AREA)

    fgmask = fgbg.apply(frame)
    cv2.imshow('frame', fgmask)

    gray_vid = cv2.cvtColor(frame, cv2.IMREAD_GRAYSCALE)
    cv2.imshow('Original', frame)

    edged_frame = cv2.Canny(frame, 1, 100)
    cv2.imshow('Edges', edged_frame)

    if cv2.waitKey(1) & 0xFF ==ord('q'):
        break

x = []
y = []

for i in range(len(height)):
    x.append(i)
    y.append(height[i])

cap.release()
cv2.destroyAllWindows()
print(x,y) 
plt.plot(x, y)  
plt.xlabel('x - axis') 
plt.ylabel('y - axis')  
plt.title('Height') 
plt.show()

【问题讨论】:

    标签: python python-3.x opencv hough-transform


    【解决方案1】:

    你只画一条线,因为你的 for 循环只在一条线上循环。

    if lines is not None:
        for line in lines: #for each line...not just one of them
            for x1,y1,x2,y2 in line:
                dot1 = (x1,y1)
                dot2 = (x2,y2)
                cv2.line(frame, dot1, dot2, (255,0,0), 3)
                length = y1 - y2
                print(length)
                height.append(length)
    

    【讨论】:

    • 当我进行更改并运行程序时,这显示 Traceback(最近一次调用):文件“main.py”,第 39 行,在 dot1 = (line[0],line [1]) IndexError: index 1 is out of bounds for axis 0 with size 1 [WARN:1] terminating async callback
    • 看看this post。我刚刚编辑了我的答案,让它看起来更像它
    • 仍然显示那些错误,更改了参数、值,但仍然相同
    • 你不应该再使用line的索引,所以如果你仍然有同样的错误,你可能错过了更新。我有一个使用我答案中的代码的单个图像的工作示例。
    • 它的工作,我的意思是它显示水平和垂直线。通过更改最大值和最小值,我可以获得更多行吗??