list index out of range的解决办法,亲测有效

项目场景:在做扫描匹配的时候,使用Vs2022发生list index out of range的报错

问题描述:

folder = argv[1]
query = cv2.imread(join(folder,"tattoo_seed.jpg"), 0)

原因分析:扫描的路径没有写清晰,导致VS也不知道去哪索引,所以发生报错;但是在VS2022也无法输入路径,所以只有在命令控制里面输入路径。

解决方案:win+r后输入cmd,进入这个界面。list index out of range的解决办法,亲测有效_第1张图片

然后输入python “你python代码存在的位置” “你扫描图片或视频的位置”
我输入的是
python “D:\opencv bob\pycv-master\chapter6\scan_for_matches.py” “D:\opencv bob\pycv-master\chapter6\anchors”
list index out of range的解决办法,亲测有效_第2张图片

list index out of range的解决办法,亲测有效_第3张图片

最后按下回车键,代码开始运行,代码运行结果就是相似的纹身输出is a match;不相似的输出is not a match。
list index out of range的解决办法,亲测有效_第4张图片
接下来贴出我的代码,有兴趣的同学可以拿走:`

from os.path import join
from os import walk
import numpy as np
import cv2
from sys import argv

# create an array of filenames
folder = argv[1]
query = cv2.imread(join(folder,"tattoo_seed.jpg"), 0)

# create files, images, descriptors globals
files = []
images = []
descriptors = []
for (dirpath, dirnames, filenames) in walk(folder):
  files.extend(filenames)
  for f in files:
    if f.endswith("npy") and f != "tattoo_seed.npy":
      descriptors.append(f)
  print (descriptors)

# create the sift detector
sift = cv2.xfeatures2d.SIFT_create()
query_kp, query_ds = sift.detectAndCompute(query, None)

# create FLANN matcher
FLANN_INDEX_KDTREE = 0
index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)
search_params = dict(checks = 50)
flann = cv2.FlannBasedMatcher(index_params, search_params)

# minimum number of matches
MIN_MATCH_COUNT = 10

potential_culprits = {}

print (">> Initiating picture scan...")
for d in descriptors:
  print( "--------- analyzing %s for matches ------------" % d)
  matches = flann.knnMatch(query_ds, np.load(join(folder, d)), k =2)
  good = []
  for m,n in matches:
      if m.distance < 0.7*n.distance:
          good.append(m)
  if len(good) > MIN_MATCH_COUNT:
    
    print ("%s is a match! (%d)" % (d, len(good)))
  else:
    print( "%s is not a match" % d)
  potential_culprits[d] = len(good)

max_matches = None
potential_suspect = None
for culprit, matches in potential_culprits.iteritems():
  if max_matches == None or matches > max_matches:
    max_matches = matches
    potential_suspect = culprit

print ("potential suspect is %s" % potential_suspect.replace("npy", "").upper())

在代码里有cv2.xfeatures2d.SIFT_create()这个函数,
如果在这发生报错,可以看看我的另一篇博客,有解决办法。over!

你可能感兴趣的:(list,数据结构)