1、将二进制文件转换为C语言数组
import os
def bin2c(path, columns=0x20):
width = columns * 4
name = os.path.splitext(os.path.basename(path))[0].upper()
with open(path, 'rb') as f1, open(f'DATA_%s.c' % name, 'w') as f2:
s = ''.join(r'\x%02x' % b for b in f1.read())
s2 = ''.join('\n "%s" // 0x%08x -> 0x%08x' % (s[i:i+width], i // 4, (i + width) // 4 - 1) for i in range(0, len(s), width))
f2.write('char* DATA_%s = (%s\n);\n' % (name, s2))
例如处理image.bin
文件,使用bin2c('image.bin')
方法调用,会生成DATA_IMAGE.c
文件。其中包含一个名为DATA_IMAGE
的数组,可在其他文件全局变量中声明extern char* DATA_IMAGE;
后调用。
生成结果类似于:
char* DATA_IMAGE = (
"\x0a\x0c\x0c\x1f\x21\x21\x1f\x24\x23\x25\x2a\x29\x3d\x43\x42\x45" // 0x00000000 -> 0x0000000f
"\x42\x43\x55\x4e\x4f\x64\x5c\x57\x6c\x64\x56\x6b\x62\x51\x66\x5d" // 0x00000010 -> 0x0000001f
"\x58\x51\x43\x55\x4e\x42\x54\x4d\x43\x55\x4e\x44\x56\x4f\x45\x57" // 0x00000020 -> 0x0000002f
"\x4c\x5f\x5c\x44\x57\x54\x48\x59\x56\x51\x62\x5f\x54\x61\x5f\x48" // 0x00000030 -> 0x0000003f
"\x3d\x39\x43\x3d\x35\x41\x3b\x37\x43\x3d\x41\x50\x48\x4f\x5e\x56" // 0x00000040 -> 0x0000004f
"\x23\x20\x1f\x2a\x27\x1d\x28\x25\x32\x40\x3c\x2b\x39\x35\x34\x42" // 0x00000050 -> 0x0000005f
"\x33\x42\x3e\x2d\x3c\x38\x2f\x3d\x39\x37\x45\x41\x3e\x49\x46\x3c" // 0x00000060 -> 0x0000006f
"\x39\x3d\x3f\x39\x40\x41\x38\x40\x41\x38\x42\x40\x38\x3f\x40\x37" // 0x00000070 -> 0x0000007f
);
2、将图片文件转换为二进制文件
import os
import cv2
import numpy
def img2bin(path)
img = cv2.imdecode(numpy.fromfile(path, numpy.uint8), -1) # 支持中文路径
# img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) # 转为灰度图
# img = cv2.resize(img, (640, 640)) # 统一尺寸
img.tofile(os.path.splitext(path)[0] + '.bin')
3、一种支持带参数调用脚本的启动方法
import sys
for path in sys.argv[1:]:
bin2c(path)