нужна строка или буфер, экземпляр найден - PullRequest
0 голосов
/ 27 мая 2018

Я только начал с python и работал над проектом, в котором я получаю сообщение «ОШИБКА: приведение к Unicode: нужна строка или буфер, экземпляр найден», изо всех сил пытаясь это исправить, но я продолжаю получать эту ошибку.

Получение ошибки в этой строке кода:

 recognise.recognizeTestDirectory(dirname, recogn, classnames, classcolors)

Ошибка:

[ObjectRecognition] ERROR: coercing to Unicode: need string or buffer, instance found
[ObjectRecognition] Exception: <type 'exceptions.TypeError'>;
File: ObjectRecognition.py;

Ниже приведены классы python и функции, которые я вызываю для передачи параметразначения для функции (признать, прямой путь)

1) ObjectRecognition.py.# вызов функции в этом классе

train = None
recogn = None    
classnames = []
classcodes = []
classcolors = []

dirname = "/Users/raj/Desktop/Pill/images/Train"
train = Training("Recogn_"+dirname, dirname, Training.AUTO_TRAINING)
recogn, classnames, classcodes = train.learning()
     if classnames:
        classcolors = create_random_colors(len(classnames))
         dirname = "/Users/raj/Desktop/Pill/images/Test"
         recognise = FileRecognizer()
         recognise.recognizeTestDirectory(dirname, recogn, classnames, classcolors)
     else:
         raise Exception("No pattern has been processed.")

2) FileRecognizer.py.# распознавание определения функции Directory

   def recognizeTestDirectory(dirname, classifier,
                       classnames = [], rect_colors = [],
                       show_stats=True, show_images=False,
                        debug = False):
            if not dirname or not os.path.isdir(dirname):
        raise IOError("Directory not found '{}'...".format(dirname))

    success = 0
    failures = 0
    filecounter = 0
    dircounter = 0
    for base, directories, files in os.walk(dirname):
        for dirs in directories:
            d = os.path.join(base, dirs)
            s, f, fc = FileRecognizer.recognizeDirectory(d, classifier, dircounter, classnames, rect_colors, False, debug)
            success += s
            failures += f
            filecounter += fc
            dircounter += 1
    if show_stats:
        print("\n-------------------------------------------------------")
        print("{:.<42}{:3d}{:>10}".format("-- @@ Processed files:",filecounter, "--"))
        print("{:.<42}{:3d}{:>10}".format("-- @@ Found and processed objects:", success + failures, "--"))
        print("{:.<42}{:3d}{:>10}".format("-- @@ Matches:", success, "-"))
        print("{:.<42}{:3d}{:>10}".format("-- @@ Errors:", failures, "-"))
        total = (success + failures)
        if total != 0:
            total = (success / total) * 100
        else:
            total = "ERROR"
        print("{:.<42}{:6.2f}%{:>6}".format("-- @@ Porcentaje de aciertos:", total, "--"))
        print("-------------------------------------------------------\n")
    return success, failures, filecounter

3) Training.py

def learning(self, debug=False):
#-> (Recognizer, [], []):
    try:
        if self.__training_path is None or not os.path.isdir(self.__training_path):
            raise IOError("Directory not found '{}'...".format(self.__training_path))

        return self.__letsTrain()

    except IOError as ioe:
        sys.stderr.write("\n[Training] I/O Error: {}.\n".format(ioe))
        return None, [], []
    except OSError as ose:
        sys.stderr.write("\n[Training] OS Error: {}.\n".format(ose))
        return None, [], []
    except Exception as e:
        sys.stderr.write("[Training] Exception: {0}.".format(e))
        return None, [], []

letsTrain (): -

def __letsTrain(self, debug=False):
    clsfr = Recognizer()
    codes = []
    samples = []
    for base, directories, files in os.walk(self.__training_path):
        c = 0
        for dirs in directories:
            self.__classcodes.append(c)
            filecount = 1
            for base2, subdir, subfiles in os.walk(os.path.join(self.__training_path, dirs)):
                print("\n--------------------------------------------------------------------------------")
                print(">>> {} <<< Processing Directory '{}':".format(c, base2))
                print("    Files to be processed: {}".format(len(subfiles)))
                proc_img = None


                clsname = ""
                if self.__mode == Training.AUTO_TRAINING:
                    clsname = dirs+"-[Cod. "+str(c)+"]"
                else: 
                    clsname = self.__getNewClassName(subfiles, base2)

                if clsname:
                    self.__classnames.append(clsname)
                    num_of_samples = 0
                    filecount = 0
                    for imagefile in subfiles:
                        (fname, fext) = os.path.splitext(imagefile)
                        if fext.lower() == ".jpg" or fext.lower() == ".png" or fext.lower() == ".bmp":
                            f = os.path.join(base2, imagefile)
                            if debug:
                                print("\n({0}.{1})-> Processing image {2} .... \n".format(dirs, filecount+1, f))
                            img = cv2.imread(f)
                            proc_img = ip.ProcessedImage(img)
                            for pattern in proc_img.descriptors:
                                pattern.classification = clsname
                                pattern.code = c
                                sample = pattern.getFeatures()
                                if sample:
                                    samples.append(sample)
                                    codes.append(pattern.code)  
                                    num_of_samples += 1  
                                else:
                                    print("  !! [Training] File '{}': \ n \ t \ t \ tA object was found from which a pattern could not be extracted ...(Value: {})".format(f, sample))
                            filecount += 1
                        else:
                            print("  !! [Training] The file '{}' it's not image (png, jpg y bmp).".format(imagefile))
                else:
                    print("  !! [Training] The subdirectory '{}' has not been processed: a valid class name has not been entered.".format(subdir))

                c += 1
                print("\n# They have been processed {} subdirectory files '{}'.".format(filecount, base2))
                print("# Assigned class '{0}': {1} processed training patterns.\n".format(clsname, num_of_samples))
                if not proc_img is None:
                    clsfr.classnames.append(clsname)
                else:
                    sys.stderr.write("\n[Training] No directory training patterns have been obtained '{}'.\n".format(dirs))

    if samples and codes:
        clsfr.train(samples, codes)
    print("\n-------------------------------------------------------------------------------")
    print("-->  The KNN classifier has been trained with {} training patterns.".format(len(samples)))
    print("-->  A total of {} classes have been created: \n {}".format(len(clsfr.classnames), clsfr.classnames))
    print("-------------------------------------------------------------------------------\n")

    # We return the classifier and the names and codes of the classes

    return clsfr, self.__classnames[:], self.__classcodes[:]

Необходимо как можно быстрее исправить эту ошибку, любая помощь будет оценена.

...