我正在尝试将包含原始数据的.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
该数据无法更改,因此如何将其从字符串转换为float而不出现错误?这是我的代码:
# 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 :(得分:0)
您已正确识别出问题所在。 0.130.0980224609375
混淆了Python,也会混淆大多数人。是0.13009 ...吗?是0.130吗?是2个十进制数字吗?是IP地址吗? Python不需要太多思考,只是耸了耸肩然后退出。此代码将假定您的意思是小数点后一位。
def clean(s):
while s.count(".") > 1:
i = s.rindex(".")
s = s[:i] + s[i+1:]
return s
assert clean("0.130.0980224609375") == "0.1300980224609375"
答案 1 :(得分:0)
所以错误是因为数字中的多余点表示它不是有效的浮点数。
如果该多余的点被错误地存在,并且您想要删除它,则可以使用:
index = y.find('.', 2) // find if there is a '.' in the string, at a position greater than 2
if(index != -1): // if there is a '.' found (find() returns -1 if the character is not found)
y = y[:index] + y[index+1:] // reconstruct the string from the section before the . and the section after
val.append(float(y))
或者,如果您只是想忽略它:
try:
val.append(float(y))
except ValueError:
pass