2017-03-25 32 views
0

私はこのOpenCVエクササイズhttp://coding-robin.de/2013/07/22/train-your-own-opencv-haar-classifier.htmlに従ってみようとしていますが、mergevec.pyを実行するためにステップに邪魔されています(私は.cppの代わりにPythonバージョンを使用します)。私はこの記事のようにPython 2.xの代わりにPython 3を持っています。Python3 TypeError: 'str'ではなくバイトのようなオブジェクトが必要です

このファイルのソースは私が得たhttps://github.com/wulfebw/mergevec/blob/master/mergevec.py

エラーが

Traceback (most recent call last): 
    File "./tools/mergevec1.py", line 96, in <module> 
    merge_vec_files(vec_directory, output_filename) 
    File "./tools/mergevec1.py", line 45, in merge_vec_files 
    val = struct.unpack('<iihh', content[:12]) 
TypeError: a bytes-like object is required, not 'str' 

だっれる私はこのpython 3.5: TypeError: a bytes-like object is required, not 'str' when writing to a fileに従うことをしようとしたとopen(f, 'r', encoding='utf-8', errors='ignore')まだ運を使用していました。

私の変更されたコードは以下の通りです:

import sys 
import glob 
import struct 
import argparse 
import traceback 


def exception_response(e): 
    exc_type, exc_value, exc_traceback = sys.exc_info() 
    lines = traceback.format_exception(exc_type, exc_value, exc_traceback) 
    for line in lines: 
     print(line) 

def get_args(): 
    parser = argparse.ArgumentParser() 
    parser.add_argument('-v', dest='vec_directory') 
    parser.add_argument('-o', dest='output_filename') 
    args = parser.parse_args() 
    return (args.vec_directory, args.output_filename) 

def merge_vec_files(vec_directory, output_vec_file): 


    # Check that the .vec directory does not end in '/' and if it does, remove it. 
    if vec_directory.endswith('/'): 
     vec_directory = vec_directory[:-1] 
    # Get .vec files 
    files = glob.glob('{0}/*.vec'.format(vec_directory)) 

    # Check to make sure there are .vec files in the directory 
    if len(files) <= 0: 
     print('Vec files to be mereged could not be found from directory: {0}'.format(vec_directory)) 
     sys.exit(1) 
    # Check to make sure there are more than one .vec files 
    if len(files) == 1: 
     print('Only 1 vec file was found in directory: {0}. Cannot merge a single file.'.format(vec_directory)) 
     sys.exit(1) 


    # Get the value for the first image size 
    prev_image_size = 0 
    try: 
     with open(files[0], 'r', encoding='utf-8', errors='ignore') as vecfile: 
      content = ''.join(str(line) for line in vecfile.readlines()) 
      val = struct.unpack('<iihh', content[:12]) 
      prev_image_size = val[1] 
    except IOError as e: 
     f = None 
     print('An IO error occured while processing the file: {0}'.format(f)) 
     exception_response(e) 


    # Get the total number of images 
    total_num_images = 0 
    for f in files: 
     try: 
      with open(f, 'r', encoding='utf-8', errors='ignore') as vecfile: 
       content = ''.join(str(line) for line in vecfile.readlines()) 
       val = struct.unpack('<iihh', content[:12]) 
       num_images = val[0] 
       image_size = val[1] 
       if image_size != prev_image_size: 
        err_msg = """The image sizes in the .vec files differ. These values must be the same. \n The image size of file {0}: {1}\n 
         The image size of previous files: {0}""".format(f, image_size, prev_image_size) 
        sys.exit(err_msg) 

       total_num_images += num_images 
     except IOError as e: 
      print('An IO error occured while processing the file: {0}'.format(f)) 
      exception_response(e) 


    # Iterate through the .vec files, writing their data (not the header) to the output file 
    # '<iihh' means 'little endian, int, int, short, short' 
    header = struct.pack('<iihh', total_num_images, image_size, 0, 0) 
    try: 
     with open(output_vec_file, 'wb') as outputfile: 
      outputfile.write(header) 

      for f in files: 
       with open(f, 'w', encoding='utf-8', errors='ignore') as vecfile: 
        content = ''.join(str(line) for line in vecfile.readlines()) 
        data = content[12:] 
        outputfile.write(data) 
    except Exception as e: 
     exception_response(e) 


if __name__ == '__main__': 
    vec_directory, output_filename = get_args() 
    if not vec_directory: 
     sys.exit('mergvec requires a directory of vec files. Call mergevec.py with -v /your_vec_directory') 
    if not output_filename: 
     sys.exit('mergevec requires an output filename. Call mergevec.py with -o your_output_filename') 

    merge_vec_files(vec_directory, output_filename) 

あなたは私が間違って何をしたか知っていますか?ありがとう。

UPDATE 1

私はこれでした:

content = b''.join(str(line) for line in vecfile.readlines()) 

を私は基本的に前に "b" を追加しました。

トレースバック(最新の呼び出しの最後):: ファイル "./tools/mergevec1.py"、97行、 merge_vec_files中(vec_directory、output_filenameに) ファイル」./toolsしかし、今私は別のエラーが発生しました//Merge_vec_filesの行44、merge_vec_filesの コンテンツ= b "'。vecfile.readlines()の行のためにstr(行)を入力します。 TypeError:シーケンスアイテム0:バイトのようなオブジェクトstrが見つかりました

+0

あなたがopeniを試してみましたあなたが引用した質問の答えに推薦するように、ファイルをモード '' rb ''で保存しますか? 'encoding'部分を削除する必要があるかもしれません。なぜなら、あなたはバイトを読み込んでいるだけで、エンコーディングは無関係であるからです。 – Craig

+0

はい 'rb'は最初にエラーを引き起こした元のコードでした。私はまたあなたの提案に基づいて、今でも '' open(files [0]、 'r'、errors = 'ignore') 'を試みました。 –

+0

'rb'は正しいです。次の行でバイトを文字列に変換し直しています。あなたのファイルの構造は何ですか?なぜあなたはラインに加わっていますか? ''' .join(...)'の代わりに 'content = vecfile.read()'を使うのはどうでしょうか? – Craig

答えて

1

示すように、コードブロックを変更してみてください:

for f in files: 
    try: 
     with open(f, 'rb') as vecfile: 
      content = vecfile.read() 
      val = struct.unpack('<iihh', content[:12]) 
      num_images = val[0] 
      image_size = val[1] 
      if image_size != prev_image_size: 
       err_msg = """The image sizes in the .vec files differ. These values must be the same. \n The image size of file {0}: {1}\n 
        The image size of previous files: {0}""".format(f, image_size, prev_image_size) 
       sys.exit(err_msg) 

      total_num_images += num_images 
    except IOError as e: 
     print('An IO error occured while processing the file: {0}'.format(f)) 
     exception_response(e) 
関連する問題