如何实现Numpy数组与字符串互转并修复转换报错
问题描述
尝试将numpy图像数组转换为字符串再还原时,出现弃用警告与ValueError报错。相关代码、运行输出及报错信息如下:
原代码
import numpy as np import matplotlib.pyplot as plt image = np.ones((28,28)) print("image: {}".format(image.shape)) string = "{}".format(image.tostring()) print("len: {}".format(len(string))) string_to_image = np.fromstring(string) print("string_to_image: {}".format(string_to_image.shape))
运行输出与报错
image: (28, 28) len: 22739 /tmp/ipykernel_2794/3542140279.py:7: DeprecationWarning: tostring() is deprecated. Use tobytes() instead. string = "{}".format(image.tostring()) /tmp/ipykernel_2794/3542140279.py:10: DeprecationWarning: The binary mode of fromstring is deprecated, as it behaves surprisingly on unicode inputs. Use frombuffer instead string_to_image = np.fromstring(string) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /tmp/ipykernel_2794/3542140279.py in <cell line: 10>() 8 print("len: {}".format(len(string))) 9 ---> 10 string_to_image = np.fromstring(string) 11 print("string_to_image: {}".format(string_to_image.shape)) ValueError: string size must be a multiple of element size
问题分析
- 弃用警告原因:
tostring()和fromstring()已被numpy官方弃用,分别推荐使用tobytes()和frombuffer()替代。 - ValueError原因:
- 原代码用
"{}".format(image.tostring())将二进制字节对象转换为了字符串表示(比如把b'\x01\x01...'变成了字符串"b'\\x01\\x01...'"),导致存储的内容是转义后的文本,而非原始二进制数据。 - 这种转义后的字符串长度不再是数组元素大小的整数倍,因此无法被
fromstring()解析为numpy数组。
- 原代码用
修复方案
直接操作二进制字节对象,避免转成字符串格式,同时替换弃用的方法:
修复后代码
import numpy as np image = np.ones((28,28)) print("原始图像形状: {}".format(image.shape)) # 直接获取二进制字节,不转成字符串 bytes_data = image.tobytes() print("二进制数据长度: {}".format(len(bytes_data))) # 从二进制字节还原数组,指定dtype并恢复形状 restored_image = np.frombuffer(bytes_data, dtype=image.dtype).reshape(image.shape) print("还原后图像形状: {}".format(restored_image.shape)) # 验证还原是否正确 print("还原结果与原数组是否一致: {}".format(np.array_equal(image, restored_image)))
代码说明
- 用
image.tobytes()获取数组的原始二进制字节,替代被弃用的tostring()。 - 存储时直接保留字节对象,避免字符串格式化带来的转义问题。
- 还原时用
np.frombuffer()替代np.fromstring(),同时指定原数组的dtype(确保解析格式正确),最后用reshape()恢复原始图像的形状。 - 新增验证步骤,确认还原后的数组与原数组完全一致。
内容的提问来源于stack exchange,提问作者stackbiz
相关产品推荐
相关产品推荐

