import cv2 file_path = "test2.bin" img = cv2.imread('grayscale_gradient_half.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) with open(file_path, "wb") as file: file.write(bytes(vals))