Python OpenCV中的ValueError

时间:2016-12-07 08:48:36

标签: python opencv

import cv2
import numpy as np

img = cv2.imread('hand.jpg',0)

height = np.size(img,0)
width = np.size(img,1)

cx = 112
cy = 131

j = 0       #initilalise
tmp=[]      #initilalise

for i in range(1,height):
    if img[i,cy]>0:
        j = j+1
        tmp.insert(j,i)
    xr = max(tmp)
    yr = cy
print tmp   
print (cr,cy)

执行上面的代码时遇到了ValueError

xr = max(tmp)
ValueError: max() arg is an empty sequence

请帮我解决上述问题

2 个答案:

答案 0 :(得分:0)

这是因为max(tmp)在执行if分支之前执行。所以,你应该检查tmp是否为空

if len(tmp) != 0:
    xr = max(tmp)

答案 1 :(得分:0)

import cv2
import numpy as np
import matplotlib.pyplot as pl

img = cv2.imread('hand.jpg',0)

height = np.size(img,0)
width = np.size(img,1)

cx = 113
cy = 130

j1 = 0      #initilalise
tmp=[]      #initilalise

for i in range(1,height):
    if img[i,cy]>0:
        j1 = j1+1
        tmp.append(i)
    if len(tmp) !=0:
        xr = max(tmp)
        yr = cy 
print (xr,yr)

上面的代码块解决了上述问题。