def __init__(self, k=1, debug=False): if get_opencv_version() == 3: self.knn = cv2.ml.KNearest_create() else: self.knn = cv2.KNearest() self.k = k self.debug = debug
def classify(self, features): if FEATURE_DATATYPE != numpy.float32: features = numpy.asarray(features, dtype=numpy.float32) if get_opencv_version() == 3: retval, result_classes, neigh_resp, dists = self.knn.findNearest(features, k=1) else: retval, result_classes, neigh_resp, dists = self.knn.find_nearest(features, k=1) return result_classes
def train(self, features, classes): if FEATURE_DATATYPE != numpy.float32: features = numpy.asarray(features, dtype=numpy.float32) if CLASS_DATATYPE != numpy.float32: classes = numpy.asarray(classes, dtype=numpy.float32) features, classes = Classifier._filter_unclassified(features, classes) if get_opencv_version() == 3: self.knn.train(features, cv2.ml.ROW_SAMPLE, classes) else: self.knn.train(features, classes)
def _segment(self, image): self.image = image image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) image = cv2.adaptiveThreshold(image, maxValue=255, adaptiveMethod=cv2.ADAPTIVE_THRESH_GAUSSIAN_C, thresholdType=cv2.THRESH_BINARY, blockSize=self.block_size, C=self.c) if get_opencv_version() == 3: _, contours, hierarchy = cv2.findContours(image, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) else: contours, hierarchy = cv2.findContours(image, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) segments = segments_to_numpy([cv2.boundingRect(c) for c in contours]) self.contours, self.hierarchy = contours, hierarchy # store, may be needed for debugging return segments