SSH服务器下图片处理的ValueError: Unable to create correctly shaped tuple from问题

在使用GAN进行图片处理时,由于FTP传输方式不当导致服务器运行时报错。文章详细介绍了错误信息及原因,指出ASCII传输模式不适用于图片文件,最终通过采用Binary模式传输图片数据集解决了问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题简述

最近要用GAN做图片处理,试跑别人的代码,因为个人电脑配置跑不动,于是搞了个服务器用GPU跑,结果没想到在本地电脑上跑没什么问题,在服务器上跑就报错,报错如下:

Traceback (most recent call last):
  File "/lib/python3.5/site-packages/numpy/lib/arraypad.py", line 1036, in _normalize_shape
    shape_arr = np.broadcast_to(shape_arr, (ndims, 2))
  File "lib/python3.5/site-packages/numpy/lib/stride_tricks.py", line 174, in broadcast_to
    return _broadcast_to(array, shape, subok=subok, readonly=True)
  File "/lib/python3.5/site-packages/numpy/lib/stride_tricks.py", line 129, in _broadcast_to
    op_flags=[op_flag], itershape=shape, order='C').itviews[0]
ValueError: operands could not be broadcast together with remapped shapes [original->remapped]: (4,2) and requested shape (1,2)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "train.py", line 90, in <module>
    validation = load_validation()
  File "/utils.py", line 77, in load_validation
    validation = np.pad(validation, pad_width=npad, mode='constant', constant_values=0)
  File "/lib/python3.5/site-packages/numpy/lib/arraypad.py", line 1295, in pad
    pad_width = _validate_lengths(narray, pad_width)
  File "/lib/python3.5/site-packages/numpy/lib/arraypad.py", line 1080, in _validate_lengths
    normshp = _normalize_shape(narray, number_elements)
  File "lib/python3.5/site-packages/numpy/lib/arraypad.py", line 1039, in _normalize_shape
    raise ValueError(fmt % (shape,))
ValueError: Unable to create correctly shaped tuple from ((0, 0), (56, 56), (0, 0), (0, 0))

 网上找了很久也没找到原因,最后苦思冥想,发现错误原因竟然是:

往服务器上传.png图片的数据集dataset的时候用了ASCII码传输。

 

网上查了一下ftp文件传输的ASCII码传输和Binary传输的差别,最后总结如下:

文本文件用ASCII码传输,图片用Binary传输。

如果用ASCII码传输图片会失真。

 

解决方案

最后把服务器上的dataset删掉,重新用Binary格式传输了一遍,问题解决了。

### 解决 Python 中 `np.fromfile` 读取 RAW 文件时的常见错误 当使用 NumPy 的 `fromfile` 函数尝试加载 RAW 格式的二进制数据文件时,可能会遇到两种主要类型的错误:`ValueError` 和 `SyntaxError`。以下是针对这两种错误的具体分析和解决方案。 --- #### **1. 关于 `ValueError: cannot reshape array of size X into shape Y`** 这种错误通常发生在试图将从文件中读取的数据重新塑形为指定形状时,数组的实际大小与目标形状不匹配。例如,在执行如下操作时可能出现此问题: ```python data = np.fromfile('example.raw', dtype=np.uint8) reshaped_data = data.reshape((height, width)) ``` 如果文件中的字节数无法整除 `(height * width)`,则会抛出 `ValueError`[^3]。 ##### **解决办法** - 验证输入文件的确切尺寸是否与预期一致。 - 在重塑之前打印并检查原始数组的长度 (`len(data)`) 是否能够被期望的高度宽度乘积所整除。 - 如果存在多余或不足的数据量,则需调整高度、宽度参数或者忽略多余的元素。 修正后的代码示例: ```python import numpy as np try: data = np.fromfile('example.raw', dtype=np.uint8) except Exception as e: print(f"An error occurred while reading the file: {e}") else: height, width = 256, 256 # Example dimensions if len(data) != height * width: raise ValueError( f"The total number of elements ({len(data)}) does not match " f"the product of desired shape ({height}x{width})." ) reshaped_data = data.reshape(height, width) ``` --- #### **2. 关于 `SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes...`** 正如先前讨论过的那样,这个错误源于未正确处理路径名中的反斜杠字符。RAW 文件路径同样容易受到这个问题的影响,尤其是在 Windows 平台上定义绝对路径的情况下。 ##### **解决办法** 采用前面提到的方法来规避路径解析过程中的转义序列冲突。下面给出一个综合运用多种技术的例子: ```python def load_raw_image(file_path, image_shape=(256, 256), pixel_dtype=np.uint8): """ Loads and reshapes a raw binary image from disk. Parameters: - file_path : str or pathlib.Path object representing the location of the .raw file. - image_shape : tuple specifying expected spatial resolution of loaded image. - pixel_dtype : Numpy type indicating how to interpret each byte/pixel value. Returns: A correctly shaped ndarray containing all pixels values extracted from given path. """ try: with open(rf"{file_path}", mode='rb') as fin: # Using raw string literals here too! flat_array = np.frombuffer(fin.read(), dtype=pixel_dtype) h, w = image_shape if len(flat_array) % (h*w) != 0: raise RuntimeError("Mismatch between actual vs declared sizes.") return flat_array.reshape(h,w) except FileNotFoundError: print("Specified filepath doesn't exist!") except OSError as err: print(err.strerror) ``` 调用上述函数时传入经过适当预处理的安全路径即可有效防止语法异常的发生。 --- ### 结论 综上所述,对于 `np.fromfile` 方法而言,首要任务是确认源数据集的真实规模及其结构特征;其次便是妥善管理涉及的操作系统特定行为比如文件地址表述形式等问题。只有这样才能确保程序稳健运行无虞。 ---
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

iteapoy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值