Select Git revision
asc2png.py 2.55 KiB
import os
import argparse
import shutil
import py7zr
import cv2
import numpy as np
def main():
parser = argparse.ArgumentParser(
'Convert asc files to png 16 bits images. To get float precision into integer, all values are multiplied by 6 before saving them as 16bits png.')
parser.add_argument('-f', '--folder', type=str, help='Folder of .asc files', default='')
parser.add_argument('--zip', type=str, help='Zipfile containing .asc files', default='')
parser.add_argument('-o', '--output', type=str, help='Output folder of .png files', default='out/')
parser.add_argument('--width', type=int, help='Width of the output image')
parser.add_argument('--height', type=int, help='Width of the output image')
parser.add_argument('--normalize', action='store_true', help='If present, normalize images before saving.')
args = parser.parse_args()
assert bool(args.folder) ^ bool(args.zip), 'Must set either --folder or --zip (not both)'
i = 0
step = 50
if args.folder:
for filename in os.listdir(args.folder):
file = os.path.join(args.folder, filename)
if os.path.join(file):
asc2png(file, args.output, args.width if args.width else None, args.height if args.height else None)
i += 1
if i % step == 0:
print(i)
elif args.zip:
with py7zr.SevenZipFile(args.zip) as z:
names = [n for n in z.getnames() if n.endswith('.asc')]
z.extract(targets=names)
for n in names:
asc2png(n, args.output, args.width if args.width else None,
args.height if args.height else None, args.normalize)
shutil.rmtree(names[0].split('/')[0])
i += 1
if i % step == 0:
print(i)
def asc2png(filepath, out_folder, width, height, normalize):
if out_folder and not os.path.isdir(out_folder):
os.mkdir(out_folder)
folder = '/'.join(filepath.split('/')[:-1])
filename = filepath.split('/')[-1].split('.')[0]
img = np.loadtxt(os.path.join(folder, filename) + '.asc', skiprows=6)
img[img < 0] = 0
if width and height:
img = cv2.resize(img, (width, height))
if normalize:
img = ((img - np.min(img)) / (np.max(img) - np.min(img))) * 65535
else:
img = (img * 6)
img_int = img.astype(np.uint16)
out = os.path.join(out_folder, f'{filename}.png')
cv2.imwrite(out, img_int)
if __name__ == '__main__':
main()