Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sourcery refactored master branch #207

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 14 additions & 14 deletions create_latex_images.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@

"""Script to render latex figure for each equation found in readme.md"""

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 52-52 refactored with the following changes:


import os
import re
import shutil
Expand All @@ -49,7 +50,7 @@

dirpath = tempfile.mkdtemp()
# ... do stuff with dirpath
print("temporary directory for latex compilation = %s" % dirpath)
print(f"temporary directory for latex compilation = {dirpath}")
if len(sys.argv) == 1:
texfile = "./readme.md"
elif len(sys.argv) == 2:
Expand All @@ -61,26 +62,25 @@
def formula_as_file(formula, file, negate=False, header=""):
laxtex_tmp_file = os.path.join(dirpath, "tmp_equation.tex")
pdf_tmp_file = os.path.join(dirpath, "tmp_equation.pdf")
latexfile = open(laxtex_tmp_file, "w")
latexfile.write("\\documentclass[preview]{standalone}")
# latexfile.write('\\input{header.tex}')
latexfile.write("\\usepackage{wasysym}")
latexfile.write("\\usepackage{amssymb}")
latexfile.write("\n\\begin{document}")
latexfile.write(" %s" % formula)
latexfile.write("\n\\end{document} ")
latexfile.close()
with open(laxtex_tmp_file, "w") as latexfile:
latexfile.write("\\documentclass[preview]{standalone}")
# latexfile.write('\\input{header.tex}')
latexfile.write("\\usepackage{wasysym}")
latexfile.write("\\usepackage{amssymb}")
latexfile.write("\n\\begin{document}")
latexfile.write(f" {formula}")
latexfile.write("\n\\end{document} ")
os.system('pdflatex -output-directory="%s" %s' % (dirpath, laxtex_tmp_file))
if file.startswith("https://rawgithub.com") or file.startswith(
"https://raw.githack.com"
):
file = "./" + re.findall(r"""/master/(.*)""", file)[0]
if file[-3:] == "svg":
os.system("pdf2svg %s %s" % (pdf_tmp_file, file))
os.system(f"pdf2svg {pdf_tmp_file} {file}")
elif file[-3:] == "pdf":
shutil.copyfile(pdf_tmp_file, file)
else:
os.system("convert -density 100 %s -quality 90 %s" % (pdf_tmp_file, file))
os.system(f"convert -density 100 {pdf_tmp_file} -quality 90 {file}")
Comment on lines -64 to +83
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function formula_as_file refactored with the following changes:



raw = open(texfile)
Expand All @@ -91,10 +91,10 @@ def formula_as_file(formula, file, negate=False, header=""):
listname = set()
for eqn in latex_equations:
if eqn[1] in listname:
raise Exception("equation image file %s already used" % eqn[1])
raise Exception(f"equation image file {eqn[1]} already used")

listname.add(eqn[1])
print("creating %s" % eqn[1])
print(f"creating {eqn[1]}")
Comment on lines -94 to +97
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 94-97 refactored with the following changes:

formula_as_file(eqn[0], eqn[1])
print("done")

Expand Down
22 changes: 8 additions & 14 deletions deodr/differentiable_renderer.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ def renderScene(
# when installed from a wheel. this also make interactive debugging easier
# for the library user

assert not (image is None)
assert not (z_buffer is None)
assert image is not None
assert z_buffer is not None
Comment on lines -26 to +27
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function renderScene refactored with the following changes:

  • Simplify logical expression using De Morgan identities (de-morgan)

height = image.shape[0]
width = image.shape[1]
nb_colors = image.shape[2]
Expand Down Expand Up @@ -107,8 +107,8 @@ def renderSceneB(
# when installed from a wheel. this also make inderactive debugginh easier
# for the library user

assert not (image is None)
assert not (z_buffer is None)
assert image is not None
assert z_buffer is not None
Comment on lines -110 to +111
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function renderSceneB refactored with the following changes:

  • Simplify logical expression using De Morgan identities (de-morgan)


height = image.shape[0]
width = image.shape[1]
Expand Down Expand Up @@ -187,7 +187,7 @@ def renderSceneB(
assert obs.shape[0] == height
assert obs.shape[1] == width
else:
assert not (image_b is None)
assert image_b is not None
assert image_b.shape[0] == height
assert image_b.shape[1] == width

Expand Down Expand Up @@ -350,9 +350,7 @@ def project_points_backward(
)
if depths_b is not None:
p_camera_b[:, 2] += depths_b
points_3d_b = p_camera_b.dot(self.extrinsic[:3, :3].T)

return points_3d_b
return p_camera_b.dot(self.extrinsic[:3, :3].T)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Camera.project_points_backward refactored with the following changes:


def get_center(self):
return -self.extrinsic[:3, :3].T.dot(self.extrinsic[:, 3])
Expand Down Expand Up @@ -763,8 +761,7 @@ def compute_vertices_luminosity(self):
directional = np.zeros((self.mesh.nb_vertices))
if self.store_backward_current is not None:
self.store_backward_current["compute_vertices_luminosity"] = directional
vertices_luminosity = directional + self.light_ambient
return vertices_luminosity
return directional + self.light_ambient
Comment on lines -766 to +764
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Scene3D.compute_vertices_luminosity refactored with the following changes:


def _compute_vertices_colors_with_illumination(self):

Expand Down Expand Up @@ -884,10 +881,7 @@ def render(self, camera, return_z_buffer=False, backface_culling=True):
self.edgeflags,
) # store this field as it could be overwritten when
# rendering several views
if return_z_buffer:
return image, z_buffer
else:
return image
return (image, z_buffer) if return_z_buffer else image
Comment on lines -887 to +884
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Scene3D.render refactored with the following changes:


def render_backward(self, image_b):
if self.perspective_correct:
Expand Down
23 changes: 8 additions & 15 deletions deodr/examples/depth_image_hand_fitting.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,23 +80,16 @@ def run(
combined_image = np.column_stack(
(depth_image, synthetic_depth, 3 * diff_image)
)
if display:
cv2.imshow("animation", cv2.resize(combined_image, None, fx=2, fy=2))
if save_images:
imsave(
os.path.join(iterfolder, f"depth_hand_iter_{niter}.png"),
combined_image,
)
if display:
cv2.imshow("animation", cv2.resize(combined_image, None, fx=2, fy=2))
if save_images:
imsave(
os.path.join(iterfolder, f"depth_hand_iter_{niter}.png"),
combined_image,
)
cv2.waitKey(1)

with open(
os.path.join(
iterfolder,
"depth_image_fitting_result_%s.json"
% str(datetime.datetime.now()).replace(":", "_"),
),
"w",
) as f:
with open(os.path.join(iterfolder, f'depth_image_fitting_result_{str(datetime.datetime.now()).replace(":", "_")}.json'), "w") as f:
Comment on lines -83 to +92
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function run refactored with the following changes:

json.dump(
{
"label": f"{dl_library} {datetime.datetime.now()}",
Expand Down
59 changes: 25 additions & 34 deletions deodr/examples/mesh_viewer.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,24 +132,23 @@ def mouse_callback(self, event, x, y, flags, param):
self.y_last = y

if self.right_is_down and not (self.ctrl_is_down):
if self.mode in ["camera_centered", "object_centered_trackball"]:
if np.abs(self.y_last - y) >= np.abs(self.x_last - x):
self.camera.extrinsic[2, 3] += self.z_translation_speed * (
self.y_last - y
)
else:
self.rotate(
[
0,
0,
-self.rotation_speed * (self.x_last - x),
]
)
self.x_last = x
self.y_last = y
if self.mode not in ["camera_centered", "object_centered_trackball"]:
raise (BaseException(f"unknown camera mode {self.mode}"))

if np.abs(self.y_last - y) >= np.abs(self.x_last - x):
self.camera.extrinsic[2, 3] += self.z_translation_speed * (
self.y_last - y
)
else:
raise (BaseException(f"unknown camera mode {self.mode}"))
self.rotate(
[
0,
0,
-self.rotation_speed * (self.x_last - x),
]
)
self.x_last = x
self.y_last = y
Comment on lines -135 to +151
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Interactor.mouse_callback refactored with the following changes:


if self.middle_is_down or (self.left_is_down and self.ctrl_is_down):
# translation
Expand All @@ -171,8 +170,7 @@ def mouse_callback(self, event, x, y, flags, param):
self.y_last = y

def print_help(self):
help_str = ""
help_str += "Mouse:\n"
help_str = "" + "Mouse:\n"
Comment on lines -174 to +173
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Interactor.print_help refactored with the following changes:

if self.mode == "object_centered_trackball":

help_str += (
Expand All @@ -190,7 +188,6 @@ def print_help(self):
help_str += "CTRL + mouse left + vertical motion: translate object along camera y axis\n"
help_str += "CTRL + mouse left + horizontal motion: translate object along camera x axis\n"

help_str += "SHIFT + mouse left + vertical motion: change the camera field of view\n"
else:
help_str += (
"mouse right + vertical motion: translate camera along its z axis\n"
Expand All @@ -204,8 +201,7 @@ def print_help(self):
)
help_str += "CTRL + mouse left + vertical motion: translate camera along its y axis\n"
help_str += "CTRL + mouse left + horizontal motion: translate camera along its x axis\n"
help_str += "SHIFT + mouse left + vertical motion: change the camera field of view\n"

help_str += "SHIFT + mouse left + vertical motion: change the camera field of view\n"
print(help_str)


Expand Down Expand Up @@ -429,8 +425,7 @@ def print_fps(self, image, fps):

def print_help(self):
"""Print the help message."""
help_str = ""
help_str += "-----------------\n"
help_str = "" + "-----------------\n"
Comment on lines -432 to +428
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Viewer.print_help refactored with the following changes:

help_str += "DEODR Mesh Viewer\n"
help_str += "-----------------\n"
help_str += "Keys:\n"
Expand Down Expand Up @@ -471,14 +466,13 @@ def toggle_lights(self):
light_directional=np.array(self.light_directional),
light_ambient=self.light_ambient,
)
elif self.use_moderngl:
self.offscreen_renderer.set_light(
light_directional=(0, 0, 0),
light_ambient=1.0,
)
else:
if self.use_moderngl:
self.offscreen_renderer.set_light(
light_directional=(0, 0, 0),
light_ambient=1.0,
)
else:
self.scene.set_light(light_directional=None, light_ambient=1.0)
self.scene.set_light(light_directional=None, light_ambient=1.0)
Comment on lines +469 to +475
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Viewer.toggle_lights refactored with the following changes:


def toggle_edge_overdraw_antialiasing(self):
"""Toggle edge overdraw anti-aliasing (DEODR rendering only)."""
Expand All @@ -487,10 +481,7 @@ def toggle_edge_overdraw_antialiasing(self):
else:
self.use_antialiasing = not (self.use_antialiasing)
print(f"use_antialiasing = {self.use_antialiasing}")
if self.use_antialiasing:
self.scene.sigma = 1.0
else:
self.scene.sigma = 0.0
self.scene.sigma = 1.0 if self.use_antialiasing else 0.0
Comment on lines -490 to +484
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Viewer.toggle_edge_overdraw_antialiasing refactored with the following changes:


def pickle_scene_and_cameras(self):
"""Save scene and camera in a pickle file."""
Expand Down
27 changes: 10 additions & 17 deletions deodr/examples/rgb_image_hand_fitting.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,26 +103,19 @@ def run(
combined_image = np.column_stack(
(hand_image, image, np.tile(diff_image[:, :, None], (1, 1, 3)))
)
if display:
cv2.imshow(
"animation",
cv2.resize(combined_image[:, :, ::-1], None, fx=2, fy=2),
)
if save_images:
imsave(
os.path.join(iterfolder, f"hand_iter_{niter}.png"), combined_image
)
if display:
cv2.imshow(
"animation",
cv2.resize(combined_image[:, :, ::-1], None, fx=2, fy=2),
)
if save_images:
imsave(
os.path.join(iterfolder, f"hand_iter_{niter}.png"), combined_image
)
cv2.waitKey(1)

# save convergence curve
with open(
os.path.join(
iterfolder,
"rgb_image_fitting_result_%s.json"
% str(datetime.datetime.now()).replace(":", "_"),
),
"w",
) as f:
with open(os.path.join(iterfolder, f'rgb_image_fitting_result_{str(datetime.datetime.now()).replace(":", "_")}.json'), "w") as f:
Comment on lines -106 to +118
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function run refactored with the following changes:

json.dump(
{
"label": f"{dl_library} {datetime.datetime.now()}",
Expand Down
29 changes: 11 additions & 18 deletions deodr/examples/rgb_multiview_hand.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,27 +110,20 @@ def run(
),
)
)
if display:
cv2.imshow(
"animation",
cv2.resize(combined_image[:, :, ::-1], None, fx=1, fy=1),
)
if save_images:
imsave(
os.path.join(iterfolder, f"hand_iter_{niter}.png"),
(combined_image * 255).astype(np.uint8),
)
if display:
cv2.imshow(
"animation",
cv2.resize(combined_image[:, :, ::-1], None, fx=1, fy=1),
)
if save_images:
imsave(
os.path.join(iterfolder, f"hand_iter_{niter}.png"),
(combined_image * 255).astype(np.uint8),
)
cv2.waitKey(1)

# save convergence curve
with open(
os.path.join(
iterfolder,
"rgb_image_fitting_result_%s.json"
% str(datetime.datetime.now()).replace(":", "_"),
),
"w",
) as f:
with open(os.path.join(iterfolder, f'rgb_image_fitting_result_{str(datetime.datetime.now()).replace(":", "_")}.json'), "w") as f:
Comment on lines -113 to +126
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function run refactored with the following changes:

json.dump(
{
"label": f"{dl_library} {datetime.datetime.now()}",
Expand Down
16 changes: 6 additions & 10 deletions deodr/examples/triangle_soup_fitting.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,9 @@ def create_example_scene(n_tri=30, width=200, height=200, clockwise=False):

if np.linalg.det(np.vstack((tmp, np.ones((3))))) > 0:
tmp = np.fliplr(tmp)
triangle = {}
triangle["ij"] = tmp.T
triangle["depths"] = np.random.rand(1) * np.ones(
triangle = {"ij": tmp.T, "depths": (np.random.rand(1) * np.ones(
(3, 1)
) # constant depth triangles to avoid collisions
))}
Comment on lines -45 to +47
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function create_example_scene refactored with the following changes:

This removes the following comments ( why? ):

# constant depth triangles to avoid collisions

triangle["textured"] = np.random.rand(1) > 0.5

if triangle["textured"]:
Expand All @@ -69,8 +67,9 @@ def create_example_scene(n_tri=30, width=200, height=200, clockwise=False):
) # all edges are discontinuity edges as no triangle pair share an edge
triangles.append(triangle)

scene = {}
for key in [
scene = {key: np.squeeze(
np.vstack([np.array(triangle[key]) for triangle in triangles])
) for key in [
"ij",
"depths",
"textured",
Expand All @@ -79,10 +78,7 @@ def create_example_scene(n_tri=30, width=200, height=200, clockwise=False):
"colors",
"shaded",
"edgeflags",
]:
scene[key] = np.squeeze(
np.vstack([np.array(triangle[key]) for triangle in triangles])
)
]}
scene["faces"] = np.arange(3 * n_tri).reshape(-1, 3).astype(np.uint32)
scene["faces_uv"] = np.arange(3 * n_tri).reshape(-1, 3).astype(np.uint32)

Expand Down
Loading