python之压缩字符数据读取解析
#!/usr/bin/python3 # -*- coding: UTF-8 -*- import struct import os # noinspection PyUnresolvedReferences import zlib # noinspection PyUnresolvedReferences import io # noinspection PyUnresolvedReferences from io import BytesIO # noinspection PyUnresolvedReferences import binascii # noinspection PyUnresolvedReferences import json # noinspection PyUnresolvedReferences import numpy # noinspection PyUnresolvedReferences #import cv2 if __name__ == '__main__': filepath='map_source.bin' binfile = open(filepath, 'rb') #打开二进制文件 size = os.path.getsize(filepath) #获得文件大小 print(size) data = binfile.read(4) #每次输出4个字节 length = struct.unpack("<i", data)[0] print(length) binfile.seek(4) data2 = binfile.read(length) # 输出39字节 data3 = zlib.decompress(data2) print("data3 size:", len(data3)) print("data3:", data3) data4 = json.loads(data3) #字符串转字典 通过字典获取 键值 print("data4: width ", data4['width']) print("data4: height ", data4['height']) width = data4['width'] height = data4['height'] binfile.seek(4+length) data_final = binfile.read(size-4-length) data_final_1 = zlib.decompress(data_final) print("data_final_1 ", len(data_final_1)) #保存原始数据 到文本txt with open("map_source.txt", "w") as f: f.write(str(width)) f.write(' ' + str(height) +'\n') for value in data_final_1: f.write(str(value)+" ") # 这句话自带文件关闭功能,不需要再写f.close() # 保存原始数据 到image # 图片I大小为3*3,灰度值全为0,也就是黑色图像 ''' Image = numpy.zeros((height, width), dtype=numpy.uint8) for row in height: for col in width: value = row * width + col Image[row, col] = data_final_1[value] cv2.imwrite("map_source.jpg", Image) ''' binfile.close()