首页 > 解决方案 > 尝试从注释文件中读取时,将字符串转换为浮点数时出现值错误

问题描述

在尝试为我自己的数据集训练模型时,我收到了这个错误:

ValueError: could not convert string to float: '281.46762 316.82224 306.0123 270.65768 136.2258 160.62991 176.29044 151.88632 तब'
File "/Users/shwaitkumar/Downloads/EAST-master/icdar.py", line 609, in generator    
text_polys, text_tags = load_annoataion(txt_fn)

如何正确地将字符串转换为浮点数?下面是加载txt格式注解的代码:

def load_annoataion(p):
    text_polys = []
    text_tags = []
    if not os.path.exists(p):
        return np.array(text_polys, dtype=np.float32)
    with open(p, 'r') as f:
        reader = csv.reader(f)
        for line in reader:
            label = line[-1]
            line = [i.strip('\ufeff').strip('\xef\xbb\xbf') for i in line]
            x1, y1, x2, y2, x3, y3, x4, y4 = list(map(float, line[:8]))
            text_polys.append([[x1, y1], [x2, y2], [x3, y3], [x4, y4]])
            if label == '*' or label == '###':
                text_tags.append(True)
            else:
                text_tags.append(False)
        return np.array(text_polys, dtype=np.float32), np.array(text_tags, dtype=np.bool)

标签: python

解决方案


你必须清理你的数据,但根据错误中的那一行,这里有一些可以帮助你的东西

def floats_from_string(line):
    nums = []
    try:
        for num in line.split(" "):
            nums.append(float(num))  # <-- cast your string to a float
    except ValueError:  # <- catch the possible non floats
        pass  # <-- don't really need them so do nothing
    return nums # <- return  list of float

推荐阅读