我正在尝试使用SURF和kNN对对象进行分类。该代码运行良好,但它偶尔会崩溃并显示“分段错误”。我不确定我是否做错了但是我很确定它已经纠正了。如果您想重现问题,这是输入文件。
import numpy as np
import cv2
import sys
trainfile = ['/home/nuntipat/Documents/Dataset/Bank/Training/15_20_front.jpg'
, '/home/nuntipat/Documents/Dataset/Bank/Training/15_50_front.jpg'
, '/home/nuntipat/Documents/Dataset/Bank/Training/15_100_front.jpg'
, '/home/nuntipat/Documents/Dataset/Bank/Training/15_500_front.jpg'
, '/home/nuntipat/Documents/Dataset/Bank/Training/15_1000_front.jpg'
, '/home/nuntipat/Documents/Dataset/Bank/Training/16_20_front.jpg'
, '/home/nuntipat/Documents/Dataset/Bank/Training/16_50_front.jpg'
, '/home/nuntipat/Documents/Dataset/Bank/Training/16_500_front.jpg']
testfile = '/home/nuntipat/Documents/Dataset/Bank/20_1.jpg'
# FLANN parameters
FLANN_INDEX_KDTREE = 0
index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)
search_params = dict(checks=50)
# Initiate FLANN matcher
flann = cv2.FlannBasedMatcher(index_params, search_params)
# Initiate SURF detector
surf = cv2.xfeatures2d.SURF_create(500)
# Create list of describtor
descriptor = []
for file in trainfile:
img = cv2.imread(file)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
kp, des = surf.detectAndCompute(gray, None)
descriptor.append(des)
# Clasify using test file
img = cv2.imread(testfile)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
kp1, des = surf.detectAndCompute(gray, None)
maxCount = 0
for i, d in enumerate(descriptor):
matches = flann.knnMatch(d, des, k=2)
count = 0
# ratio test as per Lowe's paper
for (m,n) in matches:
if m.distance < 0.7 * n.distance:
count += 1
if count > maxCount:
maxCount = count
maxMatch = i
print maxMatch
在我编写此代码之前,我尝试创建一个包含每个训练数据的kNN模型,并且只进行一次匹配。但它始终失败并导致“flann.add(descriptors)”处的分段错误。
import numpy as np
import cv2
trainfile = ['/home/nuntipat/Documents/Dataset/Bank/100_1.jpg', '/home/nuntipat/Documents/Dataset/Bank/100_2.jpg', '/home/nuntipat/Documents/Dataset/Bank/100_3.jpg']
testfile = '/home/nuntipat/Documents/Dataset/Bank/100_1.jpg'
# FLANN parameters
FLANN_INDEX_KDTREE = 0
index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)
search_params = dict(checks=50) # or pass empty dictionary
# Initiate FLANN matcher
flann = cv2.FlannBasedMatcher(index_params, search_params)
# Initiate SURF detector
surf = cv2.xfeatures2d.SURF_create()
# Train FLANN
for file in trainfile:
img = cv2.imread(file)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
keypoints, descriptors = surf.detectAndCompute(gray, None)
flann.add(descriptors)
非常感谢你的帮助。
答案 0 :(得分:1)
在失败时,可能会出现空白图像或描述符很少的图像。然后描述符矩阵为空,因此失败。
答案 1 :(得分:1)
在此链接中说明如下:
flann.add([descriptors])
http://answers.opencv.org/question/44592/flann-index-in-python-training-fails-with-segfault/
希望它有所帮助!