检查数组行是否为None并为其赋值

时间:2017-04-28 17:34:50

标签: python arrays opencv numpy houghlinesp

我正试图修复"从函数输出的数据(OpenCV v3,HoughLinesP)。第一个"行"输出总是"无" ...而其余输出似乎工作得很好。
我试图检查第一行(实际上是任何行)是"无"并为其赋值" 0"这样我就可以迭代数组了 现在我有这个(但它似乎不起作用):

import cv2
import numpy as np
import imutils 

np.set_printoptions(threshold=np.inf) #to print entire array, no truncation

LOWER_BOUND = 55   #cv2.threshold()
UPPER_BOUND = 255  #cv2.threshold()

CANNY_LOWER_BOUND = 10  #cv2.Canny()
CANNY_UPPER_BOUND = 250 #cv2.Canny()

MIN_LINE_LENGTH = 2  #HoughLinesP()
MAX_LINE_GAP = 100     #HoughLinesP() 
HOUGH_THETA = np.pi/180 #HoughLinesP() angle resolution of the accumulator, radians
HOUGH_THRESHOLD = 25 #HoughLinesP() 
HOUGH_RHO = 1         #HoughLinesP() rho, Distance resolution of the accumulator, pixels


bkgnd = cv2.bgsegm.createBackgroundSubtractorMOG()
camera = cv2.VideoCapture('/home/odroid/Desktop/python_scripts/test/test_images/Edited_Foam_Dispense_Short.mp4')

run_once = 0

while(run_once <= 1):
    (grabbed, frame) = camera.read()

    img_sub = bkgnd.apply(frame)#, learningRate = 0.001)

    canny_threshold = cv2.Canny(img_sub, CANNY_LOWER_BOUND, CANNY_UPPER_BOUND)  

    hlines = cv2.HoughLinesP(canny_threshold, HOUGH_RHO, HOUGH_THETA, MIN_LINE_LENGTH, MAX_LINE_GAP)

#************************* The if statement for the empty element*****
    if hlines is None:
        hlines[0] = [0, 0, 0, 0]
    else:

        for l in hlines:
            leftx, boty, rightx, topy = l[0]
            line = Line((leftx, boty), (rightx, topy)) 
            line.draw(frame, (0, 255, 0), 2)
#*************************************************************      

cv2.imshow('canny_threshold', canny_threshold)
cv2.imshow("frame", frame)

run_once = 1 + run_once 

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

camera.release()
cv2.destroyAllWindows()

这就是我得到的错误:

    Traceback (most recent call last):

文件&#34; test3.py&#34;,第41行,in     hlines [0] = [0,0,0,0] TypeError:&#39; NoneType&#39;对象不支持项目分配

我尝试做的是将第一行hlines分配给[[0,0,0,0]],使其与数组的其余部分匹配(意味着有数据)。为什么这不起作用?

1 个答案:

答案 0 :(得分:1)

HoughLinesP函数在第一帧返回一个空数组(返回&#34;无&#34;)。这导致了错误。添加检查以解决问题。

if hlines is None: #in case HoughLinesP fails to return a set of lines
        #make sure that this is the right shape [[ ]] and ***not*** []
        hlines = [[0,0,0,0]]
    else:
        for l in hlines:
            leftx, boty, rightx, topy = l[0]
            cv2.line(frame, (leftx, boty), (rightx, topy), (0, 255, 0), 2)