AnalyseMorphologique/utils/files/parsers.py

75 lines
2.5 KiB
Python

"""
This module contains functions to parse files.
"""
from utils.files.file_data import Object
def parse_obj_file(file_path:str, result_file_path:str = None, ratio:float = 1,normalised:str = '')->Object:
"""
Parse an OBJ file and return a dict with the vertices and faces
:param filePath: Path to the OBJ file
:param ratio: Ratio to apply to the vertices
:param cornered: If True, the vertices will be cornered
:return: A dict with the vertices and faces
"""
with open(file_path, 'r') as f:
x, y, z = [], [], []
triangles = []
data = f.readlines()
for line in data :
if line.startswith('f'):
# Face indices start at 1, not 0
triangles.append([int(line.split()[1])-1, int(line.split()[2])-1, int(line.split()[3])-1])
elif line.startswith('v'):
x.append(float(line.split()[1]) * ratio)
y.append(float(line.split()[2]) * ratio)
z.append(float(line.split()[3]) * ratio)
if 'x' in normalised:
xmin = min(x)
for count, value in enumerate(x):
x[count] -= xmin
if 'y' in normalised:
ymin = min(y)
for count, value in enumerate(y):
y[count] -= ymin
if 'z' in normalised:
zmin = min(z)
for count, value in enumerate(z):
z[count] -= zmin
return Object(list(zip(x,y,z)), triangles, result_file_path)
def parse_xyz_file(file_path: str, result_file_path:str = None, delimiter: str = ' ',normalised:str = '') -> Object:
"""
Parses an xyz file and returns a dict containing the coordinates.
:param file: The xyz file to be parsed.
:param delimiter: The delimiter used in the xyz file.
:return: A dictionary containing the coordinates.
"""
x , y , z = [], [], []
with open(file_path, 'r') as f:
data = f.readlines()
for line in data:
x.append(float(line.split(delimiter)[0]))
y.append(float(line.split(delimiter)[1]))
z.append(float(line.split(delimiter)[2]))
if 'x' in normalised:
xmin = min(x)
for count, value in enumerate(x):
x[count] -= xmin
if 'y' in normalised:
ymin = min(y)
for count, value in enumerate(y):
y[count] -= ymin
if 'z' in normalised:
zmin = min(z)
for count, value in enumerate(z):
z[count] -= zmin
return Object(list(zip(x,y,z)), result_file_path=result_file_path)