PIL save numpy array as img encounter OSError: cannot write mode F as JPEG

    科技2022-08-23  113

    Solution:

    import numpy as np from PIL import Image with open('/media/yuxijin/dataset/videos/content/mountain_2/flow/reliable_9_10.txt', 'r') as f: data = f.readlines() header = list(map(int, data[0].split(' '))) w = header[0] h = header[1] vals = np.zeros((h, w), dtype=np.float32) for i in range(1, len(data)): line = data[i].rstrip().split(' ') vals[i - 1] = np.array(list(map(np.float32, line))) img = Image.fromarray(vals) if img.mode != 'RGB': # pay attention to this line img = img.convert('RGB') # also this line img.save('test.jpg')

    Before saving the array, you have to check whether its mode is ‘RGB’ or not. If not, convert it to the ‘RGB’ mode. Then save it.

    Reference blog: PIL cannot write mode F to jpeg

    Processed: 0.045, SQL: 9