I am trying to classify objects using SURF and kNN. The code works well, but sometimes it crashes and shows "Segmentation Error". I'm not sure that I did something wrong, but I'm sure it is fixed. Here is the input file in case you want to reproduce the problem.
Link to download a dataset
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_INDEX_KDTREE = 0
index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)
search_params = dict(checks=50)
flann = cv2.FlannBasedMatcher(index_params, search_params)
surf = cv2.xfeatures2d.SURF_create(500)
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)
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
for (m,n) in matches:
if m.distance < 0.7 * n.distance:
count += 1
if count > maxCount:
maxCount = count
maxMatch = i
print maxMatch
Before I wrote this code, I tried to create a kNN model that contains all the training data and performs the match only once. However, it always fails and causes a segmentation error in "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_INDEX_KDTREE = 0
index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)
search_params = dict(checks=50)
flann = cv2.FlannBasedMatcher(index_params, search_params)
surf = cv2.xfeatures2d.SURF_create()
for file in trainfile:
img = cv2.imread(file)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
keypoints, descriptors = surf.detectAndCompute(gray, None)
flann.add(descriptors)
Thank you very much for your help.