【发布时间】:2020-07-23 16:14:04
【问题描述】:
我正在尝试将包含原始数据的 .txt 文件运行到我的代码中,但我不断收到值错误。它以前可以工作,但现在我收到此错误:
ValueError:无法将字符串转换为浮点数:'.'
这是我的原始数据文件:
0.0980224609375
0.10589599609375
0.0980224609375
0.0980224609375
0.0980224609375
0.11767578125
0.130.0980224609375 --> The error is here I assume since there are 2 periods
0.10198974609375
0.10198974609375
0.0980224609375
此数据无法更改,那么如何将其从字符串转换为浮点数而不会出错?这是我的代码:
# Read and pre-process input images
n, c, h, w = net.inputs[input_blob].shape
images = np.ndarray(shape=(n, c, h, w))
for i in range(n):
image = cv2.imread(args.input[i])
if image.shape[:-1] != (h, w):
log.warning("Image {} is resized from {} to {}".format(args.input[i], image.shape[:-1], (h, w)))
image = cv2.resize(image, (w, h))
# Swapping Red and Blue channels
#image[:, :, [0, 2]] = image[:, :, [2, 0]]
# Change data layout from HWC to CHW
image = image.transpose((2, 0, 1))
images[i] = image
eoim = image
eoim16 = eoim.astype(np.float16)
# divide by 255 to get value in range 0->1 if necessary (depends on input pixel format)
if(eoim16.max()>1.0):
eoim16 = np.divide(eoim16,255)
print(eoim16)
val = []
preprocessed_image_path = 'C:/Users/Owner/Desktop/Ubotica/IOD/cloud_detect/'
formated_image_file = "output_patch_fp"
f = open(preprocessed_image_path + "/" + formated_image_file + ".txt", 'r')
'''elem_counter = 0
for elem in eoim16:
for elem1 in elem:
for col in elem1:
#f.read(int(float(formated_image_file)))
val = float(f.readline())'''
for y in f.readlines()[0]:
val.append(float(y))
f.close()
#print(val)
#val = np.reshape(val, (3,512,512))
val = np.ndarray(shape=(c, h, w))
#res = val
# calling the instance method using the object cloudDetector
res = cloudDetector.infer(val)
res = res[out_blob]
任何帮助将不胜感激!
【问题讨论】:
-
将
0.130.0980224609375转换为浮点数意味着什么?我和 Python 都不知道。似乎生成该文件的任何程序都有错误,因此您需要修复的错误位于代码的上游。 “我怎样才能将它从字符串转换为浮点数”的答案是——你不能。它抛出一个错误,因为这是一个真正的错误情况。 -
如何转换
0.130.0980224609375?它代表什么数字? -
您希望
0.130.0980224609375转换为什么浮点值?你怎么知道其他值都没有被类似地损坏,只是没有以产生语法无效数字的方式损坏? -
@Tristan 该文件显然是由计算机生成的,而不是手动输入的,因此双句点不是拼写错误。也许它们意味着什么。您是否阅读了文件的规范?也许它讨论它。如果生成文件的计算机确实在尝试写入浮点数但插入了杂散句点,那么您真的有任何理由相信任何数字吗?将浮点文字写入文本文件很容易。它不应该有这样的错误。请注意,如果您只是删除第二个点 - 结果字符串的数字太多,不能像其他字符串一样是浮点文字。
-
最后的观察:如果应该是
0.1300980224609375,那么它相对于您显示的其他数字(围绕0.10)将是一个异常值。如果您通过删除第二个句点将其他双句点字符串解释为浮点数,它们是否也同样是不寻常的数字?
标签: python valueerror readlines