Skip to content

Commit

Permalink
message
Browse files Browse the repository at this point in the history
  • Loading branch information
issacchan26 committed Jun 8, 2023
0 parents commit 931ce32
Show file tree
Hide file tree
Showing 10 changed files with 367 additions and 0 deletions.
53 changes: 53 additions & 0 deletions annotation_output.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
from os import listdir
from os.path import isfile, isdir, join
import pandas as pd
import numpy as np

"""
Convert the annotation txt file for pyg training,
by combining the annotation txt from semantic segmentation editor and original obj file
the point order will follow the obj file
please remind that the script will not overwrite the existing file,
please clean the folder before running the script
this script will call apply_color_to_ply.py at the end, no need to run the script separately
"""


input_txt = './input_annotated_txt'
input_obj = './input_obj'
output_txt = './output_txt'

files = listdir(input_txt)

for f in sorted(files):
fullpath = join(input_txt, f)
fname = f.split('.')[0]
obj_path = input_obj + '/' + fname + '.obj'
output_path = output_txt + '/' + fname + '.txt'
if isfile(fullpath) and f.endswith('.txt'):

df1 = pd.read_csv(obj_path, sep=' ', names=['type', 'x', 'y', 'z'], on_bad_lines='skip')
df1 = df1.loc[df1['type'] == 'v']
df1 = df1.reset_index(drop=True)
df1['xyz'] = df1['x'].astype(str) + df1['y'].astype(str) + df1['z'].astype(str)
df1.set_index('xyz', inplace=True)

df2 = pd.read_csv(fullpath, sep=" ", skiprows=10, names=['x', 'y', 'z', 'label', 'object'])
df2 = df2.drop_duplicates()
df2 = df2.reset_index(drop=True)
df2['y'] = df2['y'] * (-1)
df2 = df2.round(6)
df2['xyz'] = df2['x'].map('{:,.6f}'.format) + df2['y'].map('{:,.6f}'.format) + df2['z'].map('{:,.6f}'.format)
df2.set_index('xyz', inplace=True)
df2 = df2.drop_duplicates()
df2 = df2.reindex(df1.index)
df2 = df2.drop('object', axis=1)
df2 = df2.reset_index()
df2 = df2.drop('xyz', axis=1)
df2.to_csv(output_path, header=None, index=None, sep=' ', mode='x')

import apply_color_to_ply



91 changes: 91 additions & 0 deletions apply_color_to_ply.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import sys
import pymeshlab as ml
import os
from os import listdir
from os.path import isfile, isdir, join
import pandas as pd
import numpy as np

# run "sed -i 's/[ \t]*$//' *.ply" inside folder

mypath = "./input_obj"
input_txt = './output_txt'
ply_without_color_path = "./ply_without_color"
ply_with_color_path = "./ply_with_color"
files = listdir(mypath)

color_array = [
[0, 0, 0], # rest of body
[255, 255, 51], # head
[102, 102, 0], # neck
[255, 0, 0], # right_shoulder
[255, 153, 153], # left_shoulder
[255, 128, 0], # right_upper_arm
[255, 204, 153], # left_upper_arm
[204, 0, 102], # right_elbow
[255, 102, 178], # left_elbow
[128, 255, 0], # right_fore_arm
[178, 255, 102], # left_fore_arm
[204, 0, 204], # right_wrist
[255, 102, 255], # left_wrist
[0, 204, 0], # right_hand
[102, 255, 102], # left_hand
[255, 255, 255], # main_body
[102, 0, 204], # right_hip
[204, 153, 255], # left_hip
[0, 204, 102], # right_thigh
[102, 255, 178], # left_thigh
[0, 0, 204], # right_knee
[102, 102, 255], # left_knee
[0, 204, 204], # right_leg
[153, 255, 255], # left_leg
[0, 102, 204], # right_ankle
[153, 204, 255], # left_ankle
[244, 244, 244], # right_foot
[128, 128, 128] # left_foot
]

for f in sorted(files):
fullpath = join(mypath, f)
if isfile(fullpath) and f.endswith(".obj"):

head, filename = os.path.split(f)

target_name = os.path.join(mypath, filename)

ms = ml.MeshSet()
ms.load_new_mesh(target_name)

filename = filename.split('.')[0] + '.ply'

final_name = os.path.join(ply_without_color_path, filename)
ms.save_current_mesh(final_name, binary=False, save_wedge_texcoord=False, save_vertex_color=True, save_face_color=False)

files = listdir(input_txt)

for f in sorted(files):
full_input_txt_path = join(input_txt, f)
fname = f.split('.')[0]
full_ply_without_color_path = ply_without_color_path + '/' + fname + '.ply'
output_ply_with_color_path = ply_with_color_path + '/' + fname + '.ply'

if isfile(full_input_txt_path) and f.endswith(".txt"):

df1 = pd.read_csv(full_ply_without_color_path, sep=' ', names=['x', 'y', 'z', 'r', 'g', 'b'])

df2 = pd.read_csv(full_input_txt_path, sep=' ', names=['x', 'y', 'z', 'label', 'r', 'g', 'b'])
df2 = df2.iloc[:, 3:]

for i in range(0, len(color_array)):
df2.loc[df2['label'] == i, ['r', 'g', 'b']] = color_array[i]

df2[['r', 'g', 'b']] = df2[['r', 'g', 'b']].astype('Int64')
df2.index += 10
df2 = df2.iloc[:, 1:]
df1.update(df2)
df1.loc[6.5] = ['property', 'uchar', 'red', np.nan, np.nan, np.nan]
df1.loc[6.6] = ['property', 'uchar', 'green', np.nan, np.nan, np.nan]
df1.loc[6.7] = ['property', 'uchar', 'blue', np.nan, np.nan, np.nan]
df1 = df1.sort_index().reset_index(drop=True)
df1.dropna()
df1.to_csv(output_ply_with_color_path, sep=' ', index=False, header=False, lineterminator='\n')
41 changes: 41 additions & 0 deletions mesh_reduce.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import sys
import pymeshlab as ml
import os
from os import listdir
from os.path import isfile, isdir, join

mypath = "./mesh_data"
save_path = "./output_mesh"
files = listdir(mypath)

for f in sorted(files):
fullpath = join(mypath, f)
if isfile(fullpath) and f.endswith(".obj"):
print("file:", f)
head, filename = os.path.split(f)

target_name = os.path.join(mypath, filename)

ms = ml.MeshSet()
ms.load_new_mesh(target_name)
m = ms.current_mesh()
print('input mesh has', m.vertex_number(), 'vertex and', m.face_number(), 'faces')

# Target number of vertex
TARGET = 10000

# Estimate number of faces to have 100+10000 vertex using Euler
numFaces = 100 + 2 * TARGET

# Simplify the mesh. Only first simplification will be agressive
while (ms.current_mesh().vertex_number() > TARGET):
ms.apply_filter('simplification_quadric_edge_collapse_decimation', targetfacenum=numFaces, preservenormal=True)
print("Decimated to", numFaces, "faces mesh has", ms.current_mesh().vertex_number(), "vertex")
# Refine our estimation to slowly converge to TARGET vertex number
numFaces = numFaces - (ms.current_mesh().vertex_number() - TARGET)

m = ms.current_mesh()
print('output mesh has', m.vertex_number(), 'vertex and', m.face_number(), 'faces')
final_name = os.path.join(save_path, filename)
ms.save_current_mesh(final_name)

59 changes: 59 additions & 0 deletions mesh_rigid_transform.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import pymeshlab as ml
import random
import os
from os import listdir
from os.path import isfile, isdir, join

input_path = "./mesh_data"
output_path = "./output_mesh"
files = listdir(input_path)

def rotate_mesh(input_mesh, filename):

rotate_axis = 1 # x = 0, y = 1, z = 2
rotate_angle = random.randint(-45, 45) # from 45 to -45

filename = filename.split(".")[0] + "_r_" + str(rotate_angle) + ".obj"
output_mesh = os.path.join(output_path, filename)
ms.load_new_mesh(input_mesh)
ms.apply_filter('compute_matrix_from_rotation', rotaxis=rotate_axis, rotcenter=0, angle=rotate_angle)
ms.save_current_mesh(output_mesh)
return

def translate_mesh(input_mesh, filename):

translate_distance_x = round(random.uniform(-0.50, 0.50), 2) # shift x distance from -0.50 to 0.50
translate_distance_z = round(random.uniform(-0.50, 0.50), 2) # shift z distance from -0.50 to 0.50

filename = filename.split(".")[0] + "_t_x_" + str(translate_distance_x) + "_z_" + str(translate_distance_z) + ".obj"
output_mesh = os.path.join(output_path, filename)
ms.load_new_mesh(input_mesh)
ms.apply_filter('compute_matrix_from_translation', axisx=translate_distance_x, axisz=translate_distance_z)
ms.save_current_mesh(output_mesh)
return

def scale_mesh(input_mesh, filename):

scale_parameter = round(random.uniform(0.60, 0.90), 2) # scale from 0.60 to 0.90

filename = filename.split(".")[0] + "_s_" + str(scale_parameter) + ".obj"
output_mesh = os.path.join(output_path, filename)
ms.load_new_mesh(input_mesh)
ms.apply_filter('compute_matrix_from_scaling_or_normalization', axisx=scale_parameter, uniformflag=1)
ms.save_current_mesh(output_mesh)
return

for f in sorted(files):
fullpath = join(input_path, f)
if isfile(fullpath) and f.endswith(".obj"):
head, filename = os.path.split(f)
input_mesh = os.path.join(input_path, filename)
ms = ml.MeshSet()
# rotate_mesh(input_mesh, filename)
# translate_mesh(input_mesh, filename)
scale_mesh(input_mesh, filename)





29 changes: 29 additions & 0 deletions obj_to_pcd.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import open3d as o3d
from os import listdir
from os.path import isfile, isdir, join
import numpy as np

input_path = "./input_obj"
output_path = "./output_pcd"
files = listdir(input_path)

for f in sorted(files):
fullpath = join(input_path, f)
if isfile(fullpath) and f.endswith(".obj"):
mesh = o3d.io.read_triangle_mesh(fullpath)
mesh.remove_duplicated_vertices()
mesh.remove_duplicated_triangles()

filename = f.split(".")[0]

pcd = o3d.geometry.PointCloud()
pcd.points = mesh.vertices
pcd.colors = mesh.vertex_colors
pcd.normals = mesh.vertex_normals

# R = pcd.get_rotation_matrix_from_xyz((0, np.pi / 2, 0))
# pcd.rotate(R, center=(0, 0, 0))

pcd.transform([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]) # flip upside down along y axis

o3d.io.write_point_cloud(output_path + "/" + filename + ".pcd", pcd, write_ascii=True)
27 changes: 27 additions & 0 deletions obj_to_ply.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import sys
import pymeshlab as ml
import os
from os import listdir
from os.path import isfile, isdir, join

mypath = "./input_obj"
save_path = "./output_ply"
files = listdir(mypath)

for f in sorted(files):
fullpath = join(mypath, f)
if isfile(fullpath) and f.endswith(".obj"):

head, filename = os.path.split(f)

target_name = os.path.join(mypath, filename)

ms = ml.MeshSet()
ms.load_new_mesh(target_name)
m = ms.current_mesh()

filename = filename.split('.')[0] + '.ply'

final_name = os.path.join(save_path, filename)
ms.save_current_mesh(final_name, binary=False, save_wedge_texcoord=False, save_vertex_color=True, save_face_color=False)

1 change: 1 addition & 0 deletions remove_space.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
sed -i 's/[ \t]*$//' *.ply
19 changes: 19 additions & 0 deletions shrink_flatten.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from pytorch3d.io import load_obj, load_objs_as_meshes, save_obj


def clone_of_blender_shrink_fatten(target_mesh_path_='mesh_data_folder/1/1_140.obj', scale_factor_=0.01, out_name_='temp.obj'):
chosen_meshs = load_objs_as_meshes(files=[target_mesh_path_], load_textures=False)
# print(chosen_meshs[0].verts_normals_list()[0].size())
# print(chosen_meshs[0].verts_list()[0].size())
test_subject = chosen_meshs[0].verts_normals_list()[0]*scale_factor_
# print(torch.sum(test_subject*test_subject, 1))
# print(test_subject.size())
new_mesh = chosen_meshs[0].clone()
# print(new_mesh.verts_list()[0].size())
new_mesh.verts_list()[0] = new_mesh.verts_list()[0] - test_subject
save_obj(out_name_, new_mesh.verts_list()[0], new_mesh.faces_list()[0])
return 0


if __name__ == '__main__':
clone_of_blender_shrink_fatten()
19 changes: 19 additions & 0 deletions txt_to_obj.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import os
from os import listdir
from os.path import isfile, isdir, join

mypath = "./vert_txt"
save_path = "./vert_xyz"
files = listdir(mypath)

for f in sorted(files):
fullpath = join(mypath, f)
if isfile(fullpath) and f.endswith(".txt"):
input = open(fullpath)
fout = open(save_path + "/" + f.split(".")[0] + ".xyz", "wt")
for line in input:
fout.write("%.6f %.6f %.6f\n" % (float(line.split(" ")[0]), float(line.split(" ")[1]), float(line.split(" ")[2])))
input.close()
fout.close()

import xyz_to_obj
28 changes: 28 additions & 0 deletions xyz_to_obj.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import pymeshlab as ml
import os
from os import listdir
from os.path import isfile, isdir, join

mypath = "./vert_xyz"
save_path = "./output_mesh"
files = listdir(mypath)

for f in sorted(files):
fullpath = join(mypath, f)
if isfile(fullpath) and f.endswith(".xyz"):

head, name = os.path.split(f)

target_name = os.path.join(mypath, name)

ms = ml.MeshSet()
ms.load_new_mesh(target_name)

m = ms.current_mesh()

filename = name.split(".")[0]
filename = filename+'.obj'

final_name = os.path.join(save_path, filename)
ms.save_current_mesh(final_name)

0 comments on commit 931ce32

Please sign in to comment.