Practical script 8 Python batch reads dat files and saves them as 16-bit and 8-bit grayscale images

import os
import cv2
import numpy as np


#n,m分别是图像大小,m = 320, n = 240,frame是该视频帧数,path是dat地址
def readtwo(n,m,path):
    img = np.fromfile(path,dtype=np.uint16)
    lenss=img.shape[0]
    # print(lenss/(n*m))
    frames = int(lenss/(n*m))
    img1 = np.reshape(img,(frames,n,m),order="C")
    return [img1,frames]
#进行截断,去除最高最低2%数据
def LimitHnL(Raw,frames):
    for i in range(0,frames):
        imgin = Raw[i]
        [n,m] = imgin.shape
        flatted = imgin.flatten()
        sorted_fl=sorted(flatted)
        max=sorted_fl[round(m*n*0.98)]
        min=sorted_fl[round(m*n*0.02)]
        for h in range(n):
            for j in range(m):
                if imgin[h][j] > max:
                    imgin[h][j] = max
                if imgin[h][j] < min:
                    imgin[h][j] = min
    return Raw


datafile = 'D:\\BaiduNetdiskDownload\\xzjyz\\datfile'
datanames = os.listdir(datafile)
count=1
for dataname in datanames:
    if os.path.splitext(dataname)[1] == '.dat':#目录下包含.json的文件
        print(dataname)
        suffix = dataname.split(".")[0]
        print(suffix)
        savepath = os.path.join(datafile,suffix)
        print(savepath)
        if not os.path.exists(savepath):
            os.makedirs(savepath)
        data = os.path.join(datafile,dataname)
        img1, frames = readtwo(240, 320, data)
        img = LimitHnL(img1,frames)
        for i in np.arange(frames):
            saveimg = img[i,:,:]
            # 16位转8位灰度图
            # saveimg = saveimg.astype('float16') / 65535.0
            # saveimg = saveimg * 255.0
            # saveimg = saveimg.astype('uint8')
            cv2.imwrite(savepath + '\\xzjyz' + str(count)+ str(i).zfill(4) + '.png', saveimg)
        count=count+1

Guess you like

Origin blog.csdn.net/fisherisfish/article/details/133983495