【问题标题】:Export numpy array in a for loop into one CSV in Python将for循环中的numpy数组导出到Python中的一个CSV
【发布时间】:2020-11-27 12:32:29
【问题描述】:

我有一个目录,其中包含一些转换为二进制黑白图像的图像。具有二进制像素信息(0 和 255)的 np.array 应导出到一个 CSV 文件。目录中每个图像的每个数组都应该在这个 CSV 中。

我的代码仅将循环中的最后一个数组导出到 CSV。

included_extensions = ['jpg','jpeg', 'bmp', 'png', 'gif', 'JPG']
    directory = [fn for fn in os.listdir(input_dir)
        if any(fn.endswith(ext) for ext in included_extensions)]
            
    for item in directory:
        originalImage = cv2.imread(input_dir + item)
        grayImage = cv2.cvtColor(originalImage, cv2.COLOR_BGR2GRAY)
        thresh = 128
        img_binary = cv2.threshold(grayImage, thresh, 255, cv2.THRESH_BINARY)[1]

        np.savetxt(output_dir + 'output.csv', img_binary, fmt="%d", delimiter=",")

如何获取'output.csv' 中的所有数组。最好在每个数组之间留一个空行。

【问题讨论】:

    标签: python arrays for-loop export-to-csv numpy-ndarray


    【解决方案1】:
    with open("output.csv", "a") as f:   # use 'a' instead of 'ab'
        np.savetxt(f, img_binary,  fmt="%d", delimiter=",")
        f.write("\n")
    

    您应该以附加模式打开文件。或者默认情况下 savetxt() 每次都会重写文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-12
      • 2021-11-02
      • 1970-01-01
      • 2019-07-20
      • 1970-01-01
      • 2022-01-25
      • 2020-02-27
      相关资源
      最近更新 更多