Ask Your Question

Revision history [back]

Train KNN classifier with several samples OpenCV Python

I am working on a logotype classifier/recognizer using Python 2.7.5 and OpenCV 2.4.8,

I have several images of the same logo but in different forms and presentations, I would like to train the classifier with that information and at the final recover the name of that logo regardless the form or presentation.

I would like to know how to train a KNN classifier using that information, I have the code that extracts the keypoints and descriptors using SURF, and I am storing that data directly on the hard disk.

def FeatureDetector(cvImage=None, filename=None):
  template = dict()
  hessian_threshold = 5000

  if(filename is not None):
    inputImage = cv.imread(filename)

  if(cvImage is not None):
    inputImage = cvImage

  imageGray = cv.cvtColor(inputImage, cv.COLOR_BGR2GRAY)

  detector = cv.SURF(hessian_threshold)
  keypoints, descriptors = detector.detectAndCompute(imageGray, None, useProvidedKeypoints = False)

  template["image"] = inputImage
  template["array"] = imageGray
  template["keypoints"] = keypoints
  template["descriptors"] = descriptors

  return template

def saveKeypoints(filename, keypoints):
  kArray = []

  for point in keypoints:
    keypoint = (, point.size, point.angle, point.response, point.octave, point.class_id)

  with open(filename, "wb") as outputFile:
    pickle.dump(kArray, outputFile)


def detection(logoName, extension, show=False):
  imagePath = PATHS["logos"] + logoName + "/"

    count = 1
      filename = imagePath + str(count) + "." + extension

      if(not os.path.exists(filename)):
        print "[!] File '%s' not found, the end of sequence was reached"%(filename)

      temp = FeatureDetector(filename = filename)

      saveKeypoints(PATHS["keypoints"] + inputName + "/" + str(count) + ".kp", temp["keypoints"])["descriptors"] + inputName + "/" + str(count) + ".npy", temp["descriptors"])["arrays"] + inputName + "/" + str(count) + ".npy", temp["array"])

        showFeatures(filename, temp)

      print "[O] Processed '%s'"%(filename)
      count += 1

    print "[X] Logo not found\n"


Then, I have another script that load the data and trains the KNN but only with one form of a logo. I would like to train the classifier with all the forms of the logo, using all the keypoints and descriptors that I have and recover only one result.

def loadKeypoints(path):
  keypoints = []

    with open(PATHS["keypoints"] + path + ".kp", "rb") as inputFile:
      kArray = pickle.load(inputFile)

    for point in kArray:
      feature = cv.KeyPoint(


    return False

  return keypoints

def loadSURF():

  for logo in LOGOS:
    TEMPLATES[logo] = list()
    count = 1
      path = "%s/%d"%(logo, count)

      keypoints = loadKeypoints(path)

      if(not keypoints):
        print "[!] Template for '%s' not found, the end of sequence was reached"%(path)

      descriptors = np.load(PATHS["descriptors"] + path + ".npy")
      array = np.load(PATHS["arrays"] + path + ".npy")

      template = {
        "keypoints": keypoints,
        "descriptors": descriptors,
        "array": array

      print "[O] Template loaded from %s"%(path)
      count += 1


def SURFCompare(temp, image):
  samples = temp["descriptors"]
  responses = np.arange(len(temp["keypoints"]), dtype=np.float32)

  knn = cv.KNearest()
  knn.train(samples, responses)

  for template in TEMPLATES:
    pattern = TEMPLATES[template]
    for t in pattern:
      for h, des in enumerate(t["descriptors"]):
        des = np.array(des,np.float32).reshape((1,128))
        retval, results, neigh_resp, dists = knn.find_nearest(des,1)
        res, dist = int(results[0][0]), dists[0][0]

        if dist < 0.1: # draw matched keypoints in red color
          color = (0,0,255)
          print template
        else:  # draw unmatched in blue color
          color = (255,0,0)

        #Draw matched key points on original image
        x,y = temp["keypoints"][res].pt
        center = (int(x),int(y)),center,2,color,-1)

  return True

Is that possible?
Is the KNN classifier the best approaching or there are another better options? Also I am thinking on use a FLANN matcher.

I don't know if it is the best options because actually I'm only recongnize one logo in one form but I expect to have the possibility of recognize more than one logo in several forms each one.

Thanks in advance.