将for循环中的numpy数组导出到Python中的一个CSV

Export numpy array in a for loop into one CSV in Python

我有一个目录,其中包含一些转换为二进制黑白图像的图像。带有二进制像素信息(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' 中的所有数组。最好是每个数组之间有一个空行。

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

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