【问题标题】:how to save the information on the txt file [duplicate]如何保存txt文件中的信息[重复]
【发布时间】:2020-11-15 06:47:11
【问题描述】:

我正在尝试对图像进行人物检测,但目的不是在图像上显示检测到的人,目的是将边界框的信息和置信度保存在文本文件中。所以我写 这些代码

info = open(r"output.txt","w")  
info.write(person_box) 
info.close

但它引发了错误,即TypeError: write() argument must be str, not numpy.ndarray。另外,complate 代码在下面。

def main():
    image = cv2.imread('resim.jpg')
    image = imutils.resize(image, width=600)
    bilgi =[]

    (H, W) = image.shape[:2]

    blob = cv2.dnn.blobFromImage(image, 0.007843, (W, H), 127.5)

    detector.setInput(blob)
    person_detections = detector.forward()

    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")
            
            info = open("output.txt","w")
            info.write(person_box)
            info.close
            
            print(person_box)
            print(round(confidence))

            #cv2.rectangle(image, (startX, startY), (endX, endY), (0, 0, 255), 2)
main()

当我写这个info.write(person_box,confidence) 时,它再次出现错误。 顺便说一句,除了这个问题,我还有另一个问题,我如何使用多个图像并将它们的检测信息保存在 txt 文件中。我在下面使用这些代码,但不幸的是它对我不起作用

PATH_TO_TEST_IMAGES_DIR = 'test\img'
TEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, 'image{}.jpg'.format(i)) for i in range(1, 3)]

以上代码在def main() 之外 下面的代码包括def main() 我把它放在下面两行之间。

for image_path in TEST_IMAGE_PATHS:
        image = Image.open(image_path)

【问题讨论】:

  • 请从intro tour 重复on topichow to ask。我们希望您在发布问题之前进行研究。
  • 发帖时,请提供预期的MRE。您针对 5 行问题发布了 40 行代码。请牢记本网站的目的。

标签: python file


【解决方案1】:

这是我的建议,因为您的字符串要保存一个 numpy 数组对象,请尝试将其转换为这样的字符串:

preds_string = person_box.astype("int").tostring() # Convert to string

# or you can do as such
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) # its important to add back the dtype if not the predictions look like this array([0.0e+000, 4.9e-324, 9.9e-324, 1.5e-323])

【讨论】:

    猜你喜欢
    • 2015-06-29
    • 2021-02-12
    • 1970-01-01
    • 2019-07-21
    • 1970-01-01
    • 1970-01-01
    • 2020-06-14
    • 1970-01-01
    • 2013-03-24
    相关资源
    最近更新 更多