Python cv2.KNearest() Examples

The following are 7 code examples for showing how to use cv2.KNearest(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module cv2 , or try the search function .

Example 1
def __init__(self):
        collect_dir = 'captcha/collect'
        label = []
        train_file = []
        for i in os.listdir(collect_dir):
            for y in os.listdir(collect_dir + '/' + i):
                #print i
                label.append(ord(i))
                #print y
                train_file.append(collect_dir + '/' + i + '/' + y)
        train_data = [cv2.imread(i, 0) for i in train_file]
        train = np.array(train_data).reshape(-1, 400).astype(np.float32)
        label = np.array(label).reshape(-1)
        self.knn = cv2.KNearest()
        self.knn.train(train, label) 
Example 2
Project: PyCV-time   Author: fatcloud   File: digits.py    License: MIT License 5 votes vote down vote up
def __init__(self, k = 3):
        self.k = k
        self.model = cv2.KNearest() 
Example 3
Project: PyCV-time   Author: fatcloud   File: digits.py    License: MIT License 5 votes vote down vote up
def train(self, samples, responses):
        self.model = cv2.KNearest()
        self.model.train(samples, responses) 
Example 4
Project: PyCV-time   Author: fatcloud   File: letter_recog.py    License: MIT License 5 votes vote down vote up
def __init__(self):
        self.model = cv2.KNearest() 
Example 5
Project: PyCV-time   Author: fatcloud   File: digits.py    License: MIT License 5 votes vote down vote up
def __init__(self, k = 3):
        self.k = k
        self.model = cv2.KNearest() 
Example 6
Project: PyCV-time   Author: fatcloud   File: digits.py    License: MIT License 5 votes vote down vote up
def train(self, samples, responses):
        self.model = cv2.KNearest()
        self.model.train(samples, responses) 
Example 7
Project: optimeyes   Author: LukeAllen   File: adam_descriptors.py    License: MIT License 4 votes vote down vote up
def main():
    opencv_haystack =cv2.imread('adam.jpg')
    opencv_needle = cv2.imread('adam_rightnostril.jpg')
    ngrey = cv2.cvtColor(opencv_needle, cv2.COLOR_BGR2GRAY)
    hgrey = cv2.cvtColor(opencv_haystack, cv2.COLOR_BGR2GRAY)
    import pdb
    pdb.set_trace()
    # build feature detector and descriptor extractor
    hessian_threshold = 175
    detector = cv2.SURF(hessian_threshold)
    (hkeypoints, hdescriptors) = detector.detect(hgrey, None, useProvidedKeypoints = False)
    (nkeypoints, ndescriptors) = detector.detect(ngrey, None, useProvidedKeypoints = False)

    # extract vectors of size 64 from raw descriptors numpy arrays
    rowsize = len(hdescriptors) / len(hkeypoints)
    if rowsize > 1:
        hrows = numpy.array(hdescriptors, dtype = numpy.float32).reshape((-1, rowsize))
        nrows = numpy.array(ndescriptors, dtype = numpy.float32).reshape((-1, rowsize))
        print "haystack rows shape", hrows.shape
        print "needle rows shape", nrows.shape
    else:
        print '*****************************************************8888'
        hrows = numpy.array(hdescriptors, dtype = numpy.float32)
        nrows = numpy.array(ndescriptors, dtype = numpy.float32)
        rowsize = len(hrows[0])

    # kNN training - learn mapping from hrow to hkeypoints index
    samples = hrows
    responses = numpy.arange(len(hkeypoints), dtype = numpy.float32)
    print "sample length", len(samples), "response length", len(responses)
    knn = cv2.KNearest()
    knn.train(samples,responses)

    # retrieve index and value through enumeration
    for i, descriptor in enumerate(nrows):
        descriptor = numpy.array(descriptor, dtype = numpy.float32).reshape((1, rowsize))
        print i, 'descriptor shape', descriptor.shape, 'sample shape', samples[0].shape
        retval, results, neigh_resp, dists = knn.find_nearest(descriptor, 1)
        res, dist =  int(results[0][0]), dists[0][0]
        print 'result', res, 'distance', dist

        if dist < 0.1:
            # draw matched keypoints in red color
            color = (0, 0, 255)
        else:
            # draw unmatched in blue color
            color = (255, 0, 0)
        # draw matched key points on haystack image
        x,y = hkeypoints[res].pt
        center = (int(x),int(y))
        cv2.circle(opencv_haystack,center,2,color,-1)
        # draw matched key points on needle image
        x,y = nkeypoints[i].pt
        center = (int(x),int(y))
        cv2.circle(opencv_needle,center,2,color,-1)

    cv2.imshow('haystack',opencv_haystack)
    cv2.imshow('needle',opencv_needle)
    cv2.waitKey(0)
    cv2.destroyAllWindows()