import cv2 file_path = "test3.bin" img = cv2.imread('grayscale_gradient.png', cv2.IMREAD_GRAYSCALE) height, width = img.shape vals = [] for i in range(height): for j in range(width): k = img[i, j] vals.append(k) print(f'{len(vals)} bytes') with open(file_path, "wb") as file: file.write(bytes(vals))