import os
import glob
import cv2
import scipy.misc as misc
from skimage.transform import resize
import numpy as np
from functools import reduce
from operator import mul
import torch
from torch import nn
import matplotlib.pyplot as plt
import re
try:
import cynetworkx as netx
except ImportError:
import networkx as netx
from scipy.ndimage import gaussian_filter
from skimage.feature import canny
import collections
import shutil
import imageio
import copy
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import time
from scipy.interpolate import interp1d
from collections import namedtuple
def plan_path_e2e(mesh, cc, end_pts, global_mesh, input_edge, mask, valid_map, inpaint_id, npath_map=None, fpath_map=None):
my_npath_map = np.zeros_like(input_edge) - 1
my_fpath_map = np.zeros_like(input_edge) - 1
sub_mesh = mesh.subgraph(list(cc)).copy()
ends_1, ends_2 = end_pts[0], end_pts[1]
edge_id = global_mesh.nodes[ends_1]['edge_id']
npath = [*netx.shortest_path(sub_mesh, (ends_1[0], ends_1[1]), (ends_2[0], ends_2[1]), weight='length')]
for np_node in npath:
my_npath_map[np_node[0], np_node[1]] = edge_id
fpath = []
if global_mesh.nodes[ends_1].get('far') is None:
print("None far")
else:
fnodes = global_mesh.nodes[ends_1].get('far')
dmask = mask + 0
while True:
dmask = cv2.dilate(dmask, np.ones((3, 3)), iterations=1)
ffnode = [fnode for fnode in fnodes if (dmask[fnode[0], fnode[1]] > 0 and mask[fnode[0], fnode[1]] == 0 and
global_mesh.nodes[fnode].get('inpaint_id') != inpaint_id + 1)]
if len(ffnode) > 0:
fnode = ffnode[0]
break
e_fnodes = global_mesh.nodes[ends_2].get('far')
dmask = mask + 0
while True:
dmask = cv2.dilate(dmask, np.ones((3, 3)), iterations=1)
e_ffnode = [e_fnode for e_fnode in e_fnodes if (dmask[e_fnode[0], e_fnode[1]] > 0 and mask[e_fnode[0], e_fnode[1]] == 0 and
global_mesh.nodes[e_fnode].get('inpaint_id') != inpaint_id + 1)]
if len(e_ffnode) > 0:
e_fnode = e_ffnode[0]
break
fpath.append((fnode[0], fnode[1]))
if len(e_ffnode) == 0 or len(ffnode) == 0:
return my_npath_map, my_fpath_map, [], []
barrel_dir = np.array([[1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1], [1, -1]])
n2f_dir = (int(fnode[0] - npath[0][0]), int(fnode[1] - npath[0][1]))
while True:
if barrel_dir[0, 0] == n2f_dir[0] and barrel_dir[0, 1] == n2f_dir[1]:
n2f_barrel = barrel_dir.copy()
break
barrel_dir = np.roll(barrel_dir, 1, axis=0)
for step in range(0, len(npath)):
if step == 0:
continue
elif step == 1:
next_dir = (npath[step][0] - npath[step - 1][0], npath[step][1] - npath[step - 1][1])
while True:
if barrel_dir[0, 0] == next_dir[0] and barrel_dir[0, 1] == next_dir[1]:
next_barrel = barrel_dir.copy()
break
barrel_dir = np.roll(barrel_dir, 1, axis=0)
barrel_pair = np.stack((n2f_barrel, next_barrel), axis=0)
n2f_dir = (barrel_pair[0, 0, 0], barrel_pair[0, 0, 1])
elif step > 1:
next_dir = (npath[step][0] - npath[step - 1][0], npath[step][1] - npath[step - 1][1])
while True:
if barrel_pair[1, 0, 0] == next_dir[0] and barrel_pair[1, 0, 1] == next_dir[1]:
next_barrel = barrel_pair.copy()
break
barrel_pair = np.roll(barrel_pair, 1, axis=1)
n2f_dir = (barrel_pair[0, 0, 0], barrel_pair[0, 0, 1])
new_locs = []
if abs(n2f_dir[0]) == 1:
new_locs.append((npath[step][0] + n2f_dir[0], npath[step][1]))
if abs(n2f_dir[1]) == 1:
new_locs.append((npath[step][0], npath[step][1] + n2f_dir[1]))
if len(new_locs) > 1:
new_locs = sorted(new_locs, key=lambda xx: np.hypot((xx[0] - fpath[-1][0]), (xx[1] - fpath[-1][1])))
break_flag = False
for new_loc in new_locs:
new_loc_nes = [xx for xx in [(new_loc[0] + 1, new_loc[1]), (new_loc[0] - 1, new_loc[1]),
(new_loc[0], new_loc[1] + 1), (new_loc[0], new_loc[1] - 1)]
if xx[0] >= 0 and xx[0] < my_fpath_map.shape[0] and xx[1] >= 0 and xx[1] < my_fpath_map.shape[1]]
if fpath_map is not None and np.sum([fpath_map[nlne[0], nlne[1]] for nlne in new_loc_nes]) != 0:
break_flag = True
break
if my_npath_map[new_loc[0], new_loc[1]] != -1:
continue
if npath_map is not None and npath_map[new_loc[0], new_loc[1]] != edge_id:
break_flag = True
break
fpath.append(new_loc)
if break_flag is True:
break
if (e_fnode[0], e_fnode[1]) not in fpath:
fpath.append((e_fnode[0], e_fnode[1]))
if step != len(npath) - 1:
for xx in npath[step:]:
if my_npath_map[xx[0], xx[1]] == edge_id:
my_npath_map[xx[0], xx[1]] = -1
npath = npath[:step]
if len(fpath) > 0:
for fp_node in fpath:
my_fpath_map[fp_node[0], fp_node[1]] = edge_id
code
return my_fpath_map, my_npath_map, npath, fpath
def plan_path(mesh, info_on_pix, cc, end_pt, global_mesh, input_edge, mask, valid_map, inpaint_id, npath_map=None, fpath_map=None, npath=None):
my_npath_map = np.zeros_like(input_edge) - 1
my_fpath_map = np.zeros_like(input_edge) - 1
sub_mesh = mesh.subgraph(list(cc)).copy()
pnodes = netx.periphery(sub_mesh)
ends = [*end_pt]
edge_id = global_mesh.nodes[ends[0]]['edge_id']
pnodes = sorted(pnodes,
key=lambda x: np.hypot((x[0] - ends[0][0]), (x[1] - ends[0][1])),
reverse=True)[0]
if npath is None:
npath = [*netx.shortest_path(sub_mesh, (ends[0][0], ends[0][1]), pnodes, weight='length')]
else:
if (ends[0][0], ends[0][1]) == npath[0]:
npath = npath
elif (ends[0][0], ends[0][1]) == npath[-1]:
npath = npath[::-1]
else:
import pdb; pdb.set_trace()
for np_node in npath:
my_npath_map[np_node[0], np_node[1]] = edge_id
fpath = []
if global_mesh.nodes[ends[0]].get('far') is None:
print("None far")
else:
fnodes = global_mesh.nodes[ends[0]].get('far')
dmask = mask + 0
did = 0
while True:
did += 1
if did > 3:
return my_fpath_map, my_npath_map, -1
dmask = cv2.dilate(dmask, np.ones((3, 3)), iterations=1)
ffnode = [fnode for fnode in fnodes if (dmask[fnode[0], fnode[1]] > 0 and mask[fnode[0], fnode[1]] == 0 and
global_mesh.nodes[fnode].get('inpaint_id') != inpaint_id + 1)]
if len(ffnode) > 0:
fnode = ffnode[0]
break
code
fpath.append((fnode[0], fnode[1]))
disp_diff = 0.
for n_loc in npath:
if mask[n_loc[0], n_loc[1]] != 0:
disp_diff = abs(abs(1. / info_on_pix[(n_loc[0], n_loc[1])][0]['depth']) - abs(1. / ends[0][2]))
break
barrel_dir = np.array([[1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1], [1, -1]])
n2f_dir = (int(fnode[0] - npath[0][0]), int(fnode[1] - npath[0][1]))
while True:
if barrel_dir[0, 0] == n2f_dir[0] and barrel_dir[0, 1] == n2f_dir[1]:
n2f_barrel = barrel_dir.copy()
break
barrel_dir = np.roll(barrel_dir, 1, axis=0)
for step in range(0, len(npath)):
if step == 0:
continue
elif step == 1:
next_dir = (npath[step][0] - npath[step - 1][0], npath[step][1] - npath[step - 1][1])
while True:
if barrel_dir[0, 0] == next_dir[0] and barrel_dir[0, 1] == next_dir[1]:
next_barrel = barrel_dir.copy()
break
barrel_dir = np.roll(barrel_dir, 1, axis=0)
barrel_pair = np.stack((n2f_barrel, next_barrel), axis=0)
n2f_dir = (barrel_pair[0, 0, 0], barrel_pair[0, 0, 1])
elif step > 1:
next_dir = (npath[step][0] - npath[step - 1][0], npath[step][1] - npath[step - 1][1])
while True:
if barrel_pair[1, 0, 0] == next_dir[0] and barrel_pair[1, 0, 1] == next_dir[1]:
next_barrel = barrel_pair.copy()
break
barrel_pair = np.roll(barrel_pair, 1, axis=1)
n2f_dir = (barrel_pair[0, 0, 0], barrel_pair[0, 0, 1])
new_locs = []
if abs(n2f_dir[0]) == 1:
new_locs.append((npath[step][0] + n2f_dir[0], npath[step][1]))
if abs(n2f_dir[1]) == 1:
new_locs.append((npath[step][0], npath[step][1] + n2f_dir[1]))
if len(new_locs) > 1:
new_locs = sorted(new_locs, key=lambda xx: np.hypot((xx[0] - fpath[-1][0]), (xx[1] - fpath[-1][1])))
break_flag = False
for new_loc in new_locs:
new_loc_nes = [xx for xx in [(new_loc[0] + 1, new_loc[1]), (new_loc[0] - 1, new_loc[1]),
(new_loc[0], new_loc[1] + 1), (new_loc[0], new_loc[1] - 1)]\
if xx[0] >= 0 and xx[0] < my_fpath_map.shape[0] and xx[1] >= 0 and xx[1] < my_fpath_map.shape[1]]
if fpath_map is not None and np.all([(fpath_map[nlne[0], nlne[1]] == -1) for nlne in new_loc_nes]) != True:
break_flag = True
break
if np.all([(my_fpath_map[nlne[0], nlne[1]] == -1) for nlne in new_loc_nes]) != True:
break_flag = True
break
if my_npath_map[new_loc[0], new_loc[1]] != -1:
continue
if npath_map is not None and npath_map[new_loc[0], new_loc[1]] != edge_id:
break_flag = True
break
if valid_map[new_loc[0], new_loc[1]] == 0:
break_flag = True
break
fpath.append(new_loc)
if break_flag is True:
break
if step != len(npath) - 1:
for xx in npath[step:]:
if my_npath_map[xx[0], xx[1]] == edge_id:
my_npath_map[xx[0], xx[1]] = -1
npath = npath[:step]
if len(fpath) > 0:
for fp_node in fpath:
my_fpath_map[fp_node[0], fp_node[1]] = edge_id
return my_fpath_map, my_npath_map, disp_diff
def refresh_node(old_node, old_feat, new_node, new_feat, mesh, stime=False):
mesh.add_node(new_node)
mesh.nodes[new_node].update(new_feat)
mesh.nodes[new_node].update(old_feat)
for ne in mesh.neighbors(old_node):
mesh.add_edge(new_node, ne)
if mesh.nodes[new_node].get('far') is not None:
tmp_far_nodes = mesh.nodes[new_node]['far']
for far_node in tmp_far_nodes:
if mesh.has_node(far_node) is False:
mesh.nodes[new_node]['far'].remove(far_node)
continue
if mesh.nodes[far_node].get('near') is not None:
for idx in range(len(mesh.nodes[far_node].get('near'))):
if mesh.nodes[far_node]['near'][idx][0] == new_node[0] and mesh.nodes[far_node]['near'][idx][1] == new_node[1]:
if len(mesh.nodes[far_node]['near'][idx]) == len(old_node):
mesh.nodes[far_node]['near'][idx] = new_node
if mesh.nodes[new_node].get('near') is not None:
tmp_near_nodes = mesh.nodes[new_node]['near']
for near_node in tmp_near_nodes:
if mesh.has_node(near_node) is False:
mesh.nodes[new_node]['near'].remove(near_node)
continue
if mesh.nodes[near_node].get('far') is not None:
for idx in range(len(mesh.nodes[near_node].get('far'))):
if mesh.nodes[near_node]['far'][idx][0] == new_node[0] and mesh.nodes[near_node]['far'][idx][1] == new_node[1]:
if len(mesh.nodes[near_node]['far'][idx]) == len(old_node):
mesh.nodes[near_node]['far'][idx] = new_node
if new_node != old_node:
mesh.remove_node(old_node)
if stime is False:
return mesh
else:
return mesh, None, None
def create_placeholder(context, mask, depth, fpath_map, npath_map, mesh, inpaint_id, edge_ccs, extend_edge_cc, all_edge_maps, self_edge_id):
add_node_time = 0
add_edge_time = 0
add_far_near_time = 0
valid_area = context + mask
H, W = mesh.graph['H'], mesh.graph['W']
edge_cc = edge_ccs[self_edge_id]
num_com = len(edge_cc) + len(extend_edge_cc)
hxs, hys = np.where(mask > 0)
for hx, hy in zip(hxs, hys):
mesh.add_node((hx, hy), inpaint_id=inpaint_id + 1, num_context=num_com)
for hx, hy in zip(hxs, hys):
four_nes = [(x, y) for x, y in [(hx + 1, hy), (hx - 1, hy), (hx, hy + 1), (hx, hy - 1)] if
0 <= x < mesh.graph['H'] and 0 <= y < mesh.graph['W'] and valid_area[x, y] != 0]
for ne in four_nes:
if mask[ne[0], ne[1]] != 0:
if not mesh.has_edge((hx, hy), ne):
mesh.add_edge((hx, hy), ne)
elif depth[ne[0], ne[1]] != 0:
if mesh.has_node((ne[0], ne[1], depth[ne[0], ne[1]])) and
not mesh.has_edge((hx, hy), (ne[0], ne[1], depth[ne[0], ne[1]])):
mesh.add_edge((hx, hy), (ne[0], ne[1], depth[ne[0], ne[1]]))
else:
print("Undefined context node.")
import pdb; pdb.set_trace()
near_ids = np.unique(npath_map)
if near_ids[0] == -1: near_ids = near_ids[1:]
for near_id in near_ids:
hxs, hys = np.where((fpath_map == near_id) & (mask > 0))
if hxs.shape[0] > 0:
mesh.graph['max_edge_id'] = mesh.graph['max_edge_id'] + 1
else:
break
for hx, hy in zip(hxs, hys):
mesh.nodes[(hx, hy)]['edge_id'] = int(round(mesh.graph['max_edge_id']))
four_nes = [(x, y) for x, y in [(hx + 1, hy), (hx - 1, hy), (hx, hy + 1), (hx, hy - 1)] if
x < mesh.graph['H'] and x >= 0 and y < mesh.graph['W'] and y >= 0 and npath_map[x, y] == near_id]
for xx in four_nes:
xx_n = copy.deepcopy(xx)
if not mesh.has_node(xx_n):
if mesh.has_node((xx_n[0], xx_n[1], depth[xx_n[0], xx_n[1]])):
xx_n = (xx_n[0], xx_n[1], depth[xx_n[0], xx_n[1]])
if mesh.has_edge((hx, hy), xx_n):
# pass
mesh.remove_edge((hx, hy), xx_n)
if mesh.nodes[(hx, hy)].get('near') is None:
mesh.nodes[(hx, hy)]['near'] = []
mesh.nodes[(hx, hy)]['near'].append(xx_n)
connect_point_exception = set()
hxs, hys = np.where((npath_map == near_id) & (all_edge_maps > -1))
for hx, hy in zip(hxs, hys):
unknown_id = int(round(all_edge_maps[hx, hy]))
if unknown_id != near_id and unknown_id != self_edge_id:
unknown_node = set([xx for xx in edge_ccs[unknown_id] if xx[0] == hx and xx[1] == hy])
connect_point_exception |= unknown_node
hxs, hys = np.where((npath_map == near_id) & (mask > 0))
if hxs.shape[0] > 0:
mesh.graph['max_edge_id'] = mesh.graph['max_edge_id'] + 1
else:
break
for hx, hy in zip(hxs, hys):
mesh.nodes[(hx, hy)]['edge_id'] = int(round(mesh.graph['max_edge_id']))
mesh.nodes[(hx, hy)]['connect_point_id'] = int(round(near_id))
mesh.nodes[(hx, hy)]['connect_point_exception'] = connect_point_exception
four_nes = [(x, y) for x, y in [(hx + 1, hy), (hx - 1, hy), (hx, hy + 1), (hx, hy - 1)] if
x < mesh.graph['H'] and x >= 0 and y < mesh.graph['W'] and y >= 0 and fpath_map[x, y] == near_id]
for xx in four_nes:
xx_n = copy.deepcopy(xx)
if not mesh.has_node(xx_n):
if mesh.has_node((xx_n[0], xx_n[1], depth[xx_n[0], xx_n[1]])):
xx_n = (xx_n[0], xx_n[1], depth[xx_n[0], xx_n[1]])
if mesh.has_edge((hx, hy), xx_n):
mesh.remove_edge((hx, hy), xx_n)
if mesh.nodes[(hx, hy)].get('far') is None:
mesh.nodes[(hx, hy)]['far'] = []
mesh.nodes[(hx, hy)]['far'].append(xx_n)
def max_size(mat, value=0):
if not (mat and mat[0]): return (0, 0)
it = iter(mat)
prev = [(el==value) for el in next(it)]
max_size = max_rectangle_size(prev)
for row in it:
hist = [(1+h) if el == value else 0 for h, el in zip(prev, row)]
max_size = max(max_size, max_rectangle_size(hist), key=get_area)
prev = hist
return max_size
def max_rectangle_size(histogram):
Info = namedtuple('Info', 'start height')
stack = []
top = lambda: stack[-1]
max_size = (0, 0) # height, width of the largest rectangle
pos = 0 # current position in the histogram
for pos, height in enumerate(histogram):
start = pos # position where rectangle starts
while True:
if not stack or height > top().height:
stack.append(Info(start, height)) # push
if stack and height < top().height:
max_size = max(max_size, (top().height, (pos-top().start)),
key=get_area)
start, _ = stack.pop()
continue
break # height == top().height goes here
code
pos += 1
for start, height in stack:
max_size = max(max_size, (height, (pos-start)),
key=get_area)
return max_size
def get_area(size):
return reduce(mul, size)
def find_anchors(matrix):
matrix = [[*x] for x in matrix]
mh, mw = max_size(matrix)
matrix = np.array(matrix)
# element = np.zeros((mh, mw))
for i in range(matrix.shape[0] + 1 - mh):
for j in range(matrix.shape[1] + 1 - mw):
if matrix[i:i + mh, j:j + mw].max() == 0:
return i, i + mh, j, j + mw
def find_largest_rect(dst_img, bg_color=(128, 128, 128)):
valid = np.any(dst_img[..., :3] != bg_color, axis=-1)
dst_h, dst_w = dst_img.shape[:2]
ret, labels = cv2.connectedComponents(np.uint8(valid == False))
red_mat = np.zeros_like(labels)
# denoise
for i in range(1, np.max(labels)+1, 1):
x, y, w, h = cv2.boundingRect(np.uint8(labels==i))
if x == 0 or (x+w) == dst_h or y == 0 or (y+h) == dst_w:
red_mat[labels==i] = 1
# crop
t, b, l, r = find_anchors(red_mat)
code
return t, b, l, r
The provided code consists of numerous functions for various operations related to image processing, path planning, depth handling, and graph management using a library for network graphs. Below is a brief overview of the key functions and their purposes:
Key Functions Overview:
path_planning(num_frames, x, y, z, path_type=''):
Generates a path in 3D space depending on the specified path_type (e.g., straight line, double straight line, or circular path).
Identifies the largest rectangle of non-background pixels in a given image.
Usage Context
The functions appear to support a broader framework or system, likely dealing with computer vision, particularly in 3D reconstruction tasks or scene understanding from images. They utilize:
Morphological operations (via OpenCV)
Graph structures (via networkx)
NumPy for numerical computation and manipulation
Potential Improvements
Exception handling could be added for robustness, especially for real-time applications.
Code comments and documentation could be enhanced for clarity on input/output and usage.
Performance profiling might be useful, as some functions may become a bottleneck with larger datasets.
Dependencies
The code relies on several libraries:
numpy
opencv-python (cv2)
scipy
skimage
torch (for potential deep learning models)
matplotlib
cynetworkx or networkx
This overview captures the essence of the provided code while highlighting its functions and potential use cases in image processing and computer vision applications.
To modify a camera path planning function to include rotation capability, the first step is to define how you want to represent the camera's orientation. One common way to represent camera rotation in 3D space is through Euler angles or quaternions. For simplicity, I will add the ability to define camera rotations based on Euler angles along with the existing position path planning.
Let's modify the path_planning function to include rotation parameters. For this example, I will add rotation around the Y-axis (yaw), allow you to specify the number of frames for the rotation, and calculate the corresponding rotation values at each frame.
Here is the modified path_planning function:
python
def path_planning(num_frames, x, y, z, rotate_y=None, path_type=''):
if path_type == 'straight-line':
corner_points = np.array([[0, 0, 0], [(0 + x) * 0.5, (0 + y) * 0.5, (0 + z) * 0.5], [x, y, z]])
corner_t = np.linspace(0, 1, len(corner_points))
t = np.linspace(0, 1, num_frames)
cs = interp1d(corner_t, corner_points, axis=0, kind='quadratic')
spline = cs(t)
xs, ys, zs = [xx.squeeze() for xx in np.split(spline, 3, 1)]
elif path_type == 'double-straight-line':
corner_points = np.array([[-x, -y, -z], [0, 0, 0], [x, y, z]])
corner_t = np.linspace(0, 1, len(corner_points))
t = np.linspace(0, 1, num_frames)
cs = interp1d(corner_t, corner_points, axis=0, kind='quadratic')
spline = cs(t)
xs, ys, zs = [xx.squeeze() for xx in np.split(spline, 3, 1)]
elif path_type == 'circle':
xs, ys, zs = [], [], []
for frame_id, bs_shift_val in enumerate(np.arange(-2.0, 2.0, (4./num_frames))):
xs += [np.cos(bs_shift_val * np.pi) * 1 * x]
ys += [np.sin(bs_shift_val * np.pi) * 1 * y]
zs += [np.cos(bs_shift_val * np.pi/2.) * 1 * z]
xs, ys, zs = np.array(xs), np.array(ys), np.array(zs)
# Handle camera rotation
if rotate_y is not None:
# Rotate around Y by specified angle
rotation_angles = np.linspace(0, rotate_y, num_frames)
rotation_matrix = np.array([[np.cos(rotation_angles), 0, -np.sin(rotation_angles)],
[0, 1, 0],
[np.sin(rotation_angles), 0, np.cos(rotation_angles)]])
# Apply rotation to the positions
rotated_positions = np.array([
np.dot(rotation_matrix[:, :, i], np.array([xs[i], ys[i], zs[i]]))
for i in range(num_frames)
])
# Update xs, ys, zs with the rotated values
xs, ys, zs = rotated_positions[:, 0], rotated_positions[:, 1], rotated_positions[:, 2]
return xs, ys, zs
Changes Made:
Added rotate_y Parameter: This parameter specifies the total rotation angle around the Y-axis (yaw) in degrees or radians.
Rotation Logic:
Created a rotation matrix using the specified angles.
Rotated the calculated positions (xs, ys, zs) based on these angles.
Usage Example:
When you call this modified path_planning function, you can specify the rotation angle you wish to apply. For example, if you want to rotate the camera by 90 degrees while moving along the specified path, simply call:
python
num_frames = 100
x, y, z = 5, 5, 5
rotate_y = 90 # Rotate 90 degrees around Y-axis
xs, ys, zs = path_planning(num_frames, x, y, z, rotate_y=rotate_y, path_type='straight-line')
Notes:
You may need to further refine rotation parameters depending on how you want the camera to behave, including pitch and roll if needed.
Make sure to adjust visualization and camera setup in whatever rendering or visualization framework you are using to visualize these positions and rotations correctly.