我正在开展一个项目,我必须在叶子上发现一些疾病。为此,我要检测显着的特征,即叶子(在我的情况下)并删除图像的背景。我有以下代码。
import cv2, sys
import numpy as np
def backproject(source, target, levels = 2, scale = 1):
hsv = cv2.cvtColor(source, cv2.COLOR_BGR2HSV)
hsvt = cv2.cvtColor(target, cv2.COLOR_BGR2HSV)
# calculating object histogram
roihist = cv2.calcHist([hsv],[0, 1], None, [levels, levels], [0, 180, 0, 256] )
# normalize histogram and apply backprojection
cv2.normalize(roihist,roihist,0,255,cv2.NORM_MINMAX)
dst = cv2.calcBackProject([hsvt],[0,1],roihist,[0,180,0,256], scale)
return dst
def saliency_by_backprojection(img):
cv2.pyrMeanShiftFiltering(img, 2, 10, img, 4)
backproj = np.uint8(backproject(img, img, levels = 2))
cv2.normalize(backproj,backproj,0,255,cv2.NORM_MINMAX)
saliencies = [backproj, backproj, backproj]
saliency = cv2.merge(saliencies)
cv2.pyrMeanShiftFiltering(saliency, 20, 200, saliency, 2)
saliency = cv2.cvtColor(saliency, cv2.COLOR_BGR2GRAY)
cv2.equalizeHist(saliency, saliency)
return 255-saliency
def saliency_map(img):
saliency_hsv = saliency_by_backprojection(img * 1)
saliency = saliency_hsv
(T, saliency) = cv2.threshold(saliency, 200, 255, cv2.THRESH_BINARY)
return saliency
def largest_contours_rect(saliency):
contours, hierarchy = cv2.findContours(saliency * 1,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
contours = sorted(contours, key = cv2.contourArea)
return cv2.boundingRect(contours[-1])
def refine_saliency_with_grabcut(img, saliency):
rect = largest_contours_rect(saliency)
bgdmodel = np.zeros((1, 65),np.float64)
fgdmodel = np.zeros((1, 65),np.float64)
saliency[np.where(saliency > 0)] = cv2.GC_FGD
mask = saliency
cv2.grabCut(img, mask, rect, bgdmodel, fgdmodel, 1, cv2.GC_INIT_WITH_RECT)
mask = np.where((mask==2)|(mask==0),0,1).astype('uint8')
return mask
def backprojection_saliency(img):
saliency = saliency_map(img)
mask = refine_saliency_with_grabcut(img, saliency)
return mask
if __name__ == "__main__":
name = sys.argv[1].strip('k5.jpg')
img = cv2.imread(sys.argv[1], 1)
img = cv2.resize(img, (640/2, 480/2))
mask = backprojection_saliency(img)
segmentation = img*mask[:,:,np.newaxis]
cv2.imshow("original", img)
cv2.imshow("segmentation", segmentation)
cv2.waitKey(-1)
由于我是Python和openCV的新手,我无法解决以下错误。
Traceback (most recent call last):
File "F:\FYP\Code\saliency-from-backproj-master\saliency.py", line
56, in <module>
name = sys.argv[1].strip('k5.jpg')
IndexError: list index out of range
为什么会这样?
答案 0 :(得分:0)
您没有提供任何命令行参数。
argv变量包含传递给程序的命令行参数。与python your_script.py verbose print
时一样,argv
变量包含['your_script.py', 'verbose', 'print']
。
但是,如果您只提供python your_script.py
argv包含['your_script.py']
(只有一个元素argv [0])。因此,致电argv[1]
是IndexError
。
sys.agv上的Python文档:
<强> sys.argv中强>
传递给Python脚本的命令行参数列表。 argv [0]是脚本名称(无论这是否是完整路径名,它依赖于操作系统)。如果使用解释器的-c命令行选项执行命令,则将argv [0]设置为字符串'-c'。如果没有脚本名称传递给Python解释器,则argv [0]为空字符串。