无论我使用sys.argv做什么[1:];我似乎无法接受以下脚本来接受它。我已经尝试将sys.argv从列表转换为单个字符串,并且在调用detect()函数时仍然会返回错误。有线索吗?
import cv2
import sys
def detect(path):
img = cv2.imread(path)
cascade = cv2.CascadeClassifier("haarcascade_frontalface_alt.xml")
rects = cascade.detectMultiScale(img, 1.3, 4, cv2.cv.CV_HAAR_SCALE_IMAGE, (20,20))
if len(rects) == 0:
return [], img
rects[:, 2:] += rects[:, :2]
return rects, img
def box(rects, img):
for x1, y1, x2, y2 in rects:
cv2.rectangle(img, (x1, y1), (x2, y2), (127, 255, 0), 2)
cv2.imwrite('detected1.jpg', img);
file = sys.argv[1:]
#file = 'image.jpg'
print sys.argv[1:]
rects, img = detect(file)
box(rects, img)
答案 0 :(得分:1)
file
不等于'image.jpg'
,因为sys.argv
是参数的列表,而[1:]
只创建一个新列表:
>>> argv = ['script_name.py', 'image.jpg']
>>> file = argv[1:]
>>> file
['image.jpg']
>>> type(file)
<class 'list'>
>>>
您应该将sys.argv
列表编入索引,而不是使用切片表示法来提取文件名:
>>> argv = ['script_name.py', 'image.jpg']
>>> file = argv[1] # Notice there is no :
>>> file
'image.jpg'
>>> type(file)
<class 'str'>
>>>
答案 1 :(得分:1)
sys.argv
是字符串列表,而不是单个字符串。所以sys.argv[1:]
也是一个列表,而不是一个字符串,这可能是失败的原因。也许你的意思是sys.argv[1]
?
答案 2 :(得分:1)
sys.argv[1:]
是每个参数的列表。因此,当它传递给detect
时,您尝试从列表中加载图像,而不是文件名。
你要么只想拿第一个参数:
file = sys.argv[1]
或者为每个参数执行操作:
for file in sys.argv[1:]:
rects, img = detect(file)
box(rects, img)