Python3 TypeError:需要类似字节的对象,而不是str

2024-10-01 11:29:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图遵循这个OpenCV练习http://coding-robin.de/2013/07/22/train-your-own-opencv-haar-classifier.html,但在运行步骤上遇到了问题mergevec.py(我使用Python版本而不是.cpp版本)。我用的是python3,而不是本文中的python2.x。在

此文件的源是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'),但仍然没有运气。在

我修改的代码如下:

^{pr2}$

你知道我做错什么了吗?谢谢。在

更新1

我这样做了:

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

我基本上在前面加了“b”。但是,现在我得到了一个不同的错误:

回溯(最近一次呼叫): 文件“./tools/mergevec1.py”,第97行,in 合并\u vec_文件(vec_目录,输出_文件名) 文件“./tools/mergevec1.py”,第44行,在merge_-vec_文件中 content=b''。为line-in连接(str(line)向量文件.readlines()) TypeError:序列项0:应为类似字节的对象,但找到str


Tags: 文件inpy版本错误linemergecontent
1条回答
网友
1楼 · 发布于 2024-10-01 11:29:12

正如OP解释的那样,该文件包含二进制数据。要使用二进制数据:

  1. 文件应该以二进制模式打开,方法是使用'rb'作为 open调用中的模式。在
  2. 打开文件后,使用.read() 而不是.readlines()来读取数据。这就避免了 .readlines()处理行的方式导致数据损坏 结束字符。在
  3. 避免将字节数组转换为 字符数组(字符串)。在

对于问题中提供的代码,读取图像的代码部分应为:

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)

相关问题 更多 >