问题描述
我必须通过命令行输入几个参数。例如通过命令行的tileGridSize,clipLimit等。这是我的代码的样子;
#!/usr/bin/env python
import numpy as np
import cv2 as cv
import sys #import Sys.
import matplotlib.pyplot as plt
img = cv.imread(sys.argv[1],0) # reads image as grayscale
clipLimit = float(sys.argv[2])
tileGridSize = tuple(sys.argv[3])
clahe = cv.createCLAHE(clipLimit,tileGridSize)
cl1 = clahe.apply(img)
# show image
cv.imshow('image',cl1)
cv.waitKey(0)
cv.destroyAllWindows()
如果我在下面传递参数(我想给(8,8)元组);
python testing.py picture.jpg 3.0 8 8
TypeError: function takes exactly 2 arguments (1 given)
解决方法
我建议您研究argparse
,这是处理命令行的标准软件包,但严格使用sys.argv
:
import sys
print(sys.argv[1],float(sys.argv[2]),tuple(map(int,sys.argv[3:])))
$ python testing.py picture.jpg 3.0 8 8
> picture.jpg 3.0 (8,8)
会发生什么:
-
sys.argv[3:]
获取所有参数的列表,包括第4个及之后的数字(索引3
) -
map(int,sys.argv[3:])
将int
函数应用于列表中的所有项目 -
tuple(...)
将map
的生成器转换为适当的元组