-1

The following is my code of writing facial landmarks to files:

import face_alignment, os
from skimage import io

fa = face_alignment.FaceAlignment(face_alignment.LandmarksType._3D, flip_input=False, device='cpu')
dir = os.listdir('/home/onur/Downloads/datasets/headsegmentation_final/Training/Images/')

for image in dir:
    try:
        input = io.imread('/home/onur/Downloads/datasets/headsegmentation_final/Training/Images/' + image)
        preds = fa.get_landmarks(input)
        if preds != None:
            print(preds)
            f = open('/home/onur/Downloads/datasets/headsegmentation_final/Training/Images/' + image[:-4] + '_landmark.txt', 'w')
            f.write(preds)
            f.write('\n')
    except:
        pass

The output of preds is this:

[array([[ 51.       , 122.       , -24.98454  ],
       [ 53.       , 145.       , -26.51761  ],
       [ 58.       , 164.       , -28.835543 ],
       [ 64.       , 183.       , -29.486448 ],
       [ 72.       , 198.       , -25.393326 ],   
...])]

But the returned files are empty. Where am I going wrong?

Onur-Andros Ozbek
  • 2,998
  • 2
  • 29
  • 78
  • Does this answer your question? [Saving numpy array to txt file row wise](https://stackoverflow.com/questions/9565426/saving-numpy-array-to-txt-file-row-wise) – tevemadar Mar 26 '22 at 16:00

1 Answers1

1

I would guess buffering is enabled, and you never close the file. As a result, nothing ends up getting written. Should do the writing part like this:

with open('/home/onur/Downloads/datasets/headsegmentation_final/Training/Images/' + image[:-4] + '_landmark.txt', 'w') as f:
    f.write(preds)
    f.write('\n')

Using the with context manager will automatically close the file when you exit the block, which should also flush anything in the buffer.

wmorrell
  • 4,988
  • 4
  • 27
  • 37