Search code examples
pythonarraysfor-loopexport-to-csvnumpy-ndarray

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


I have a directory with a few images that are converted to binary black and white images. The np.array with the binary pixel information (0 and 255) should be exported to one CSV file. Every array from every image in the directory should be in this CSV.

My code exports only the last array in the loop to 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=",")

How can I get all arrays in the 'output.csv'. The best would be one empty row between every array.


Solution

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

    You should open your file in append mode. Or by default savetxt() rewrites the file everytime.