编程语言
首页 > 编程语言> > OpenCV Python:使用FlannBasedMatcher时偶尔会出现分段错误

OpenCV Python:使用FlannBasedMatcher时偶尔会出现分段错误

作者:互联网

我正在尝试使用SURF和kNN对​​对象进行分类.该代码运行良好,但它偶尔会崩溃并显示“分段错误”.我不确定我是否做错了但是我很确定它已经纠正了.如果要重现问题,这是输入文件.

Link to download the 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 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)

非常感谢你的帮助.

解决方法:

在它失败的时候,可能存在空白图像或具有很少描述符的图像.然后描述符矩阵为空,因此失败.

标签:python,opencv,surf,flann
来源: https://codeday.me/bug/20190702/1361350.html