【问题标题】:how to save integer valuses to the text file如何将整数值保存到文本文件
【发布时间】:2020-11-15 10:25:10
【问题描述】:

我正在尝试检测图像上的人,目的是将边界框和置信度值的信息作为具有相应置信度和边界框的值保存到文本文件中。但我收到错误TypeError: write() argument must be str, not bytes TypeError: write() argument must be str, not numpy.ndarray

 for i in np.arange(0, person_detections.shape[2]):
        confidence = person_detections[0, 0, i, 2]
        if confidence > 0.5:
            idx = int(person_detections[0, 0, i, 1])

            if CLASSES[idx] != "person":
                continue

            person_box = person_detections[0, 0, i, 3:7] * np.array([W, H, W, H])
            (startX, startY, endX, endY) = person_box.astype("int")
                        
            preds = np.append(person_box, confidence) # Add confidence to array
            preds_string = preds.tostring() # Convert array to string

            # To convert back to numpy array
            bbox = np.fromstring(preds_string, dtype=int) 
            
            info = open("output.txt","w")
            info.write(bbox)
            info.close

我无法将它们保存并写入文本文件,这是我上面的代码,如果可能,我将不胜感激,谢谢

【问题讨论】:

    标签: python loops file detection


    【解决方案1】:

    错误告诉您不能将numpy.ndarray 类型的对象传递给write(也就是说,您不能按照您尝试的方式将数组写入文本文件)。 numpy 具有相应的功能(请参阅 numpy.savetxt)。

    >>> import numpy as np
    >>>
    >>> preds_string = '1 2'
    >>> bbox = np.fromstring(preds_string, dtype=int, sep=' ')
    >>>
    >>> with open("output.txt","w") as info:
    ...     np.savetxt(info, bbox, fmt='%d')
    ... 
    
    $ cat output.txt      
    1
    2
    

    【讨论】:

    • 我们也可以这样做var3 = " ".join([str(person_box), str(confidence)]) myText = open(r'output.txt','w') myText.write(var3) myText.close()
    猜你喜欢
    • 1970-01-01
    • 2018-12-31
    • 2011-04-02
    • 1970-01-01
    • 1970-01-01
    • 2016-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多