id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
6,328
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 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 path_planning(num_frames, x, y, z, 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) return xs, ys, zs def get_MiDaS_samples(image_folder, depth_folder, config, specific=None, aft_certain=None): lines = [os.path.splitext(os.path.basename(xx))[0] for xx in glob.glob(os.path.join(image_folder, '*' + config['img_format']))] samples = [] generic_pose = np.eye(4) assert len(config['traj_types']) == len(config['x_shift_range']) ==\ len(config['y_shift_range']) == len(config['z_shift_range']) == len(config['video_postfix']), \ "The number of elements in 'traj_types', 'x_shift_range', 'y_shift_range', 'z_shift_range' and \ 'video_postfix' should be equal." tgt_pose = [[generic_pose * 1]] tgts_poses = [] for traj_idx in range(len(config['traj_types'])): tgt_poses = [] sx, sy, sz = path_planning(config['num_frames'], config['x_shift_range'][traj_idx], config['y_shift_range'][traj_idx], config['z_shift_range'][traj_idx], path_type=config['traj_types'][traj_idx]) for xx, yy, zz in zip(sx, sy, sz): tgt_poses.append(generic_pose * 1.) tgt_poses[-1][:3, -1] = np.array([xx, yy, zz]) tgts_poses += [tgt_poses] tgt_pose = generic_pose * 1 aft_flag = True if aft_certain is not None and len(aft_certain) > 0: aft_flag = False for seq_dir in lines: if specific is not None and len(specific) > 0: if specific != seq_dir: continue if aft_certain is not None and len(aft_certain) > 0: if aft_certain == seq_dir: aft_flag = True if aft_flag is False: continue samples.append({}) sdict = samples[-1] sdict['depth_fi'] = os.path.join(depth_folder, seq_dir + config['depth_format']) sdict['ref_img_fi'] = os.path.join(image_folder, seq_dir + config['img_format']) H, W = imageio.imread(sdict['ref_img_fi']).shape[:2] sdict['int_mtx'] = np.array([[max(H, W), 0, W//2], [0, max(H, W), H//2], [0, 0, 1]]).astype(np.float32) if sdict['int_mtx'].max() > 1: sdict['int_mtx'][0, :] = sdict['int_mtx'][0, :] / float(W) sdict['int_mtx'][1, :] = sdict['int_mtx'][1, :] / float(H) sdict['ref_pose'] = np.eye(4) sdict['tgt_pose'] = tgt_pose sdict['tgts_poses'] = tgts_poses sdict['video_postfix'] = config['video_postfix'] sdict['tgt_name'] = [os.path.splitext(os.path.basename(sdict['depth_fi']))[0]] sdict['src_pair_name'] = sdict['tgt_name'][0] return samples
null
6,329
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 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 read_MiDaS_depth(disp_fi, disp_rescale=10., h=None, w=None): if 'npy' in os.path.splitext(disp_fi)[-1]: disp = np.load(disp_fi) else: disp = imageio.imread(disp_fi).astype(np.float32) disp = disp - disp.min() disp = cv2.blur(disp / disp.max(), ksize=(3, 3)) * disp.max() disp = (disp / disp.max()) * disp_rescale if h is not None and w is not None: disp = resize(disp / disp.max(), (h, w), order=1) * disp.max() depth = 1. / np.maximum(disp, 0.05) return depth
null
6,330
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 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 follow_image_aspect_ratio(depth, image): H, W = image.shape[:2] image_aspect_ratio = H / W dH, dW = depth.shape[:2] depth_aspect_ratio = dH / dW if depth_aspect_ratio > image_aspect_ratio: resize_H = dH resize_W = dH / image_aspect_ratio else: resize_W = dW resize_H = dW * image_aspect_ratio depth = resize(depth / depth.max(), (int(resize_H), int(resize_W)), order=0) * depth.max() return depth
null
6,331
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 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 depth_resize(depth, origin_size, image_size): if origin_size[0] is not 0: max_depth = depth.max() depth = depth / max_depth depth = resize(depth, origin_size, order=1, mode='edge') depth = depth * max_depth else: max_depth = depth.max() depth = depth / max_depth depth = resize(depth, image_size, order=1, mode='edge') depth = depth * max_depth return depth
null
6,332
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 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 filter_irrelevant_edge(self_edge, other_edges, other_edges_with_id, current_edge_id, context, edge_ccs, mesh, anchor): other_edges = other_edges.squeeze() other_edges_with_id = other_edges_with_id.squeeze() self_edge = self_edge.squeeze() dilate_self_edge = cv2.dilate(self_edge.astype(np.uint8), np.array([[1,1,1],[1,1,1],[1,1,1]]).astype(np.uint8), iterations=1) edge_ids = collections.Counter(other_edges_with_id.flatten()).keys() other_edges_info = [] # import ipdb # ipdb.set_trace() for edge_id in edge_ids: edge_id = int(edge_id) if edge_id >= 0: condition = ((other_edges_with_id == edge_id) * other_edges * context).astype(np.uint8) if dilate_self_edge[condition > 0].sum() == 0: other_edges[other_edges_with_id == edge_id] = 0 else: num_condition, condition_labels = cv2.connectedComponents(condition, connectivity=8) for condition_id in range(1, num_condition): isolate_condition = ((condition_labels == condition_id) > 0).astype(np.uint8) num_end_group, end_group = cv2.connectedComponents(((dilate_self_edge * isolate_condition) > 0).astype(np.uint8), connectivity=8) if num_end_group == 1: continue for end_id in range(1, num_end_group): end_pxs, end_pys = np.where((end_group == end_id)) end_px, end_py = end_pxs[0], end_pys[0] other_edges_info.append({}) other_edges_info[-1]['edge_id'] = edge_id # other_edges_info[-1]['near_depth'] = None other_edges_info[-1]['diff'] = None other_edges_info[-1]['edge_map'] = np.zeros_like(self_edge) other_edges_info[-1]['end_point_map'] = np.zeros_like(self_edge) other_edges_info[-1]['end_point_map'][(end_group == end_id)] = 1 other_edges_info[-1]['forbidden_point_map'] = np.zeros_like(self_edge) other_edges_info[-1]['forbidden_point_map'][(end_group != end_id) * (end_group != 0)] = 1 other_edges_info[-1]['forbidden_point_map'] = cv2.dilate(other_edges_info[-1]['forbidden_point_map'], kernel=np.array([[1,1,1],[1,1,1],[1,1,1]]), iterations=2) for x in edge_ccs[edge_id]: nx = x[0] - anchor[0] ny = x[1] - anchor[1] if nx == end_px and ny == end_py: # other_edges_info[-1]['near_depth'] = abs(nx) if mesh.nodes[x].get('far') is not None and len(mesh.nodes[x].get('far')) == 1: other_edges_info[-1]['diff'] = abs(1./abs([*mesh.nodes[x].get('far')][0][2]) - 1./abs(x[2])) else: other_edges_info[-1]['diff'] = 0 # if end_group[nx, ny] != end_id and end_group[nx, ny] > 0: # continue try: if isolate_condition[nx, ny] == 1: other_edges_info[-1]['edge_map'][nx, ny] = 1 except: pass try: other_edges_info = sorted(other_edges_info, key=lambda x : x['diff'], reverse=True) except: import pdb pdb.set_trace() # import pdb # pdb.set_trace() # other_edges = other_edges[..., None] for other_edge in other_edges_info: if other_edge['end_point_map'] is None: import pdb pdb.set_trace() other_edges = other_edges * context return other_edges, other_edges_info
null
6,333
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 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 vis_depth_edge_connectivity(depth, config): disp = 1./depth u_diff = (disp[1:, :] - disp[:-1, :])[:-1, 1:-1] b_diff = (disp[:-1, :] - disp[1:, :])[1:, 1:-1] l_diff = (disp[:, 1:] - disp[:, :-1])[1:-1, :-1] r_diff = (disp[:, :-1] - disp[:, 1:])[1:-1, 1:] u_over = (np.abs(u_diff) > config['depth_threshold']).astype(np.float32) b_over = (np.abs(b_diff) > config['depth_threshold']).astype(np.float32) l_over = (np.abs(l_diff) > config['depth_threshold']).astype(np.float32) r_over = (np.abs(r_diff) > config['depth_threshold']).astype(np.float32) concat_diff = np.stack([u_diff, b_diff, r_diff, l_diff], axis=-1) concat_over = np.stack([u_over, b_over, r_over, l_over], axis=-1) over_diff = concat_diff * concat_over pos_over = (over_diff > 0).astype(np.float32).sum(-1).clip(0, 1) neg_over = (over_diff < 0).astype(np.float32).sum(-1).clip(0, 1) neg_over[(over_diff > 0).astype(np.float32).sum(-1) > 0] = 0 _, edge_label = cv2.connectedComponents(pos_over.astype(np.uint8), connectivity=8) T_junction_maps = np.zeros_like(pos_over) for edge_id in range(1, edge_label.max() + 1): edge_map = (edge_label == edge_id).astype(np.uint8) edge_map = np.pad(edge_map, pad_width=((1,1),(1,1)), mode='constant') four_direc = np.roll(edge_map, 1, 1) + np.roll(edge_map, -1, 1) + np.roll(edge_map, 1, 0) + np.roll(edge_map, -1, 0) eight_direc = np.roll(np.roll(edge_map, 1, 1), 1, 0) + np.roll(np.roll(edge_map, 1, 1), -1, 0) + \ np.roll(np.roll(edge_map, -1, 1), 1, 0) + np.roll(np.roll(edge_map, -1, 1), -1, 0) eight_direc = (eight_direc + four_direc)[1:-1,1:-1] pos_over[eight_direc > 2] = 0 T_junction_maps[eight_direc > 2] = 1 _, edge_label = cv2.connectedComponents(pos_over.astype(np.uint8), connectivity=8) edge_label = np.pad(edge_label, 1, mode='constant') return edge_label
null
6,334
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 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 find_anchors(matrix): 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) return t, b, l, r
null
6,335
import os import numpy as np import networkx as netx import matplotlib.pyplot as plt from functools import partial from vispy import scene, io from vispy.scene import visuals from vispy.visuals.filters import Alpha import cv2 from moviepy.editor import ImageSequenceClip from skimage.transform import resize import time import copy import torch import os from inpaint.utils import path_planning, open_small_mask, clean_far_edge, refine_depth_around_edge from inpaint.utils import refine_color_around_edge, filter_irrelevant_edge_new, require_depth_edge, clean_far_edge_new from inpaint.utils import create_placeholder, refresh_node, find_largest_rect from inpaint.mesh_tools import get_depth_from_maps, get_map_from_ccs, get_edge_from_nodes, get_depth_from_nodes, get_rgb_from_nodes, crop_maps_by_size, convert2tensor, recursive_add_edge, update_info, filter_edge, relabel_node, depth_inpainting from inpaint.mesh_tools import refresh_bord_depth, enlarge_border, fill_dummy_bord, extrapolate, fill_missing_node, incomplete_node, get_valid_size, dilate_valid_size, size_operation import transforms3d import random from functools import reduce import struct import tqdm import sys def calculate_fov_FB(mesh): mesh.graph['aspect'] = mesh.graph['H'] / mesh.graph['W'] if mesh.graph['H'] > mesh.graph['W']: mesh.graph['hFov'] = 0.508015513 half_short = np.tan(mesh.graph['hFov']/2.0) half_long = half_short * mesh.graph['aspect'] mesh.graph['vFov'] = 2.0 * np.arctan(half_long) else: mesh.graph['vFov'] = 0.508015513 half_short = np.tan(mesh.graph['vFov']/2.0) half_long = half_short / mesh.graph['aspect'] mesh.graph['hFov'] = 2.0 * np.arctan(half_long) return mesh
null
6,336
import os import numpy as np import networkx as netx import matplotlib.pyplot as plt from functools import partial from vispy import scene, io from vispy.scene import visuals from vispy.visuals.filters import Alpha import cv2 from moviepy.editor import ImageSequenceClip from skimage.transform import resize import time import copy import torch import os from inpaint.utils import path_planning, open_small_mask, clean_far_edge, refine_depth_around_edge from inpaint.utils import refine_color_around_edge, filter_irrelevant_edge_new, require_depth_edge, clean_far_edge_new from inpaint.utils import create_placeholder, refresh_node, find_largest_rect from inpaint.mesh_tools import get_depth_from_maps, get_map_from_ccs, get_edge_from_nodes, get_depth_from_nodes, get_rgb_from_nodes, crop_maps_by_size, convert2tensor, recursive_add_edge, update_info, filter_edge, relabel_node, depth_inpainting from inpaint.mesh_tools import refresh_bord_depth, enlarge_border, fill_dummy_bord, extrapolate, fill_missing_node, incomplete_node, get_valid_size, dilate_valid_size, size_operation import transforms3d import random from functools import reduce import struct import tqdm import sys def reproject_3d_int_detail_FB(sx, sy, z, w_offset, h_offset, mesh): if mesh.graph.get('tan_hFov') is None: mesh.graph['tan_hFov'] = np.tan(mesh.graph['hFov'] / 2.) if mesh.graph.get('tan_vFov') is None: mesh.graph['tan_vFov'] = np.tan(mesh.graph['vFov'] / 2.) ray = np.array([(-1. + 2. * ((sy+0.5-w_offset)/(mesh.graph['W'] - 1))) * mesh.graph['tan_hFov'], (1. - 2. * (sx+0.5-h_offset)/(mesh.graph['H'] - 1)) * mesh.graph['tan_vFov'], -1]) point_3d = ray * np.abs(z) return point_3d
null
6,337
import os import numpy as np import networkx as netx import matplotlib.pyplot as plt from functools import partial from vispy import scene, io from vispy.scene import visuals from vispy.visuals.filters import Alpha import cv2 from moviepy.editor import ImageSequenceClip from skimage.transform import resize import time import copy import torch import os from inpaint.utils import path_planning, open_small_mask, clean_far_edge, refine_depth_around_edge from inpaint.utils import refine_color_around_edge, filter_irrelevant_edge_new, require_depth_edge, clean_far_edge_new from inpaint.utils import create_placeholder, refresh_node, find_largest_rect from inpaint.mesh_tools import get_depth_from_maps, get_map_from_ccs, get_edge_from_nodes, get_depth_from_nodes, get_rgb_from_nodes, crop_maps_by_size, convert2tensor, recursive_add_edge, update_info, filter_edge, relabel_node, depth_inpainting from inpaint.mesh_tools import refresh_bord_depth, enlarge_border, fill_dummy_bord, extrapolate, fill_missing_node, incomplete_node, get_valid_size, dilate_valid_size, size_operation import transforms3d import random from functools import reduce import struct import tqdm import sys def reproject_3d_int(sx, sy, z, mesh): k = mesh.graph['cam_param_pix_inv'].copy() if k[0, 2] > 0: k = np.linalg.inv(k) ray = np.dot(k, np.array([sy-mesh.graph['woffset'], sx-mesh.graph['hoffset'], 1]).reshape(3, 1)) point_3d = ray * np.abs(z) point_3d = point_3d.flatten() return point_3d
null
6,338
import os import numpy as np import networkx as netx import matplotlib.pyplot as plt from functools import partial from vispy import scene, io from vispy.scene import visuals from vispy.visuals.filters import Alpha import cv2 from moviepy.editor import ImageSequenceClip from skimage.transform import resize import time import copy import torch import os from inpaint.utils import path_planning, open_small_mask, clean_far_edge, refine_depth_around_edge from inpaint.utils import refine_color_around_edge, filter_irrelevant_edge_new, require_depth_edge, clean_far_edge_new from inpaint.utils import create_placeholder, refresh_node, find_largest_rect from inpaint.mesh_tools import get_depth_from_maps, get_map_from_ccs, get_edge_from_nodes, get_depth_from_nodes, get_rgb_from_nodes, crop_maps_by_size, convert2tensor, recursive_add_edge, update_info, filter_edge, relabel_node, depth_inpainting from inpaint.mesh_tools import refresh_bord_depth, enlarge_border, fill_dummy_bord, extrapolate, fill_missing_node, incomplete_node, get_valid_size, dilate_valid_size, size_operation import transforms3d import random from functools import reduce import struct import tqdm import sys def judge_dangle(mark, mesh, node): if not (1 <= node[0] < mesh.graph['H']-1) or not(1 <= node[1] < mesh.graph['W']-1): return mark mesh_neighbors = [*mesh.neighbors(node)] mesh_neighbors = [xx for xx in mesh_neighbors if 0 < xx[0] < mesh.graph['H'] - 1 and 0 < xx[1] < mesh.graph['W'] - 1] if len(mesh_neighbors) >= 3: return mark elif len(mesh_neighbors) <= 1: mark[node[0], node[1]] = (len(mesh_neighbors) + 1) else: dan_ne_node_a = mesh_neighbors[0] dan_ne_node_b = mesh_neighbors[1] if abs(dan_ne_node_a[0] - dan_ne_node_b[0]) > 1 or \ abs(dan_ne_node_a[1] - dan_ne_node_b[1]) > 1: mark[node[0], node[1]] = 3 return mark
null
6,339
import os import numpy as np import json import scipy.misc as misc import scipy.signal as signal import matplotlib.pyplot as plt import cv2 import scipy.misc as misc from skimage import io from functools import partial from vispy import scene, io from vispy.scene import visuals from functools import reduce import scipy.misc as misc from vispy.visuals.filters import Alpha import cv2 from skimage.transform import resize import copy import torch import os from inpaint.utils import refine_depth_around_edge, smooth_cntsyn_gap from inpaint.utils import require_depth_edge, filter_irrelevant_edge_new, open_small_mask from skimage.feature import canny from scipy import ndimage import time import transforms3d def get_union_size(mesh, dilate, *alls_cc): all_cc = reduce(lambda x, y: x | y, [set()] + [*alls_cc]) min_x, min_y, max_x, max_y = mesh.graph['H'], mesh.graph['W'], 0, 0 H, W = mesh.graph['H'], mesh.graph['W'] for node in all_cc: if node[0] < min_x: min_x = node[0] if node[0] > max_x: max_x = node[0] if node[1] < min_y: min_y = node[1] if node[1] > max_y: max_y = node[1] max_x = max_x + 1 max_y = max_y + 1 # mask_size = dilate_valid_size(mask_size, edge_dict['mask'], dilate=[20, 20]) osize_dict = dict() osize_dict['x_min'] = max(0, min_x - dilate[0]) osize_dict['x_max'] = min(H, max_x + dilate[0]) osize_dict['y_min'] = max(0, min_y - dilate[1]) osize_dict['y_max'] = min(W, max_y + dilate[1]) return osize_dict
null
6,340
import os import numpy as np import json import scipy.misc as misc import scipy.signal as signal import matplotlib.pyplot as plt import cv2 import scipy.misc as misc from skimage import io from functools import partial from vispy import scene, io from vispy.scene import visuals from functools import reduce import scipy.misc as misc from vispy.visuals.filters import Alpha import cv2 from skimage.transform import resize import copy import torch import os from inpaint.utils import refine_depth_around_edge, smooth_cntsyn_gap from inpaint.utils import require_depth_edge, filter_irrelevant_edge_new, open_small_mask from skimage.feature import canny from scipy import ndimage import time import transforms3d def incomplete_node(mesh, edge_maps, info_on_pix): vis_map = np.zeros((mesh.graph['H'], mesh.graph['W'])) for node in mesh.nodes: if mesh.nodes[node].get('synthesis') is not True: connect_all_flag = False nes = [xx for xx in mesh.neighbors(node) if mesh.nodes[xx].get('synthesis') is not True] if len(nes) < 3 and 0 < node[0] < mesh.graph['H'] - 1 and 0 < node[1] < mesh.graph['W'] - 1: if len(nes) <= 1: connect_all_flag = True else: dan_ne_node_a = nes[0] dan_ne_node_b = nes[1] if abs(dan_ne_node_a[0] - dan_ne_node_b[0]) > 1 or \ abs(dan_ne_node_a[1] - dan_ne_node_b[1]) > 1: connect_all_flag = True if connect_all_flag == True: vis_map[node[0], node[1]] = len(nes) four_nes = [(node[0] - 1, node[1]), (node[0] + 1, node[1]), (node[0], node[1] - 1), (node[0], node[1] + 1)] for ne in four_nes: for info in info_on_pix[(ne[0], ne[1])]: ne_node = (ne[0], ne[1], info['depth']) if info.get('synthesis') is not True and mesh.has_node(ne_node): mesh.add_edge(node, ne_node) break return mesh
null
6,341
import os import numpy as np import json import scipy.misc as misc import scipy.signal as signal import matplotlib.pyplot as plt import cv2 import scipy.misc as misc from skimage import io from functools import partial from vispy import scene, io from vispy.scene import visuals from functools import reduce import scipy.misc as misc from vispy.visuals.filters import Alpha import cv2 from skimage.transform import resize import copy import torch import os from inpaint.utils import refine_depth_around_edge, smooth_cntsyn_gap from inpaint.utils import require_depth_edge, filter_irrelevant_edge_new, open_small_mask from skimage.feature import canny from scipy import ndimage import time import transforms3d def get_edge_from_nodes(context_cc, erode_context_cc, mask_cc, edge_cc, extend_edge_cc, H, W, mesh): context = np.zeros((H, W)) mask = np.zeros((H, W)) rgb = np.zeros((H, W, 3)) disp = np.zeros((H, W)) depth = np.zeros((H, W)) real_depth = np.zeros((H, W)) edge = np.zeros((H, W)) comp_edge = np.zeros((H, W)) fpath_map = np.zeros((H, W)) - 1 npath_map = np.zeros((H, W)) - 1 near_depth = np.zeros((H, W)) for node in context_cc: rgb[node[0], node[1]] = np.array(mesh.nodes[node]['color']) disp[node[0], node[1]] = mesh.nodes[node]['disp'] depth[node[0], node[1]] = node[2] context[node[0], node[1]] = 1 for node in erode_context_cc: rgb[node[0], node[1]] = np.array(mesh.nodes[node]['color']) disp[node[0], node[1]] = mesh.nodes[node]['disp'] depth[node[0], node[1]] = node[2] context[node[0], node[1]] = 1 rgb = rgb / 255. disp = np.abs(disp) disp = disp / disp.max() real_depth = depth.copy() for node in context_cc: if mesh.nodes[node].get('real_depth') is not None: real_depth[node[0], node[1]] = mesh.nodes[node]['real_depth'] for node in erode_context_cc: if mesh.nodes[node].get('real_depth') is not None: real_depth[node[0], node[1]] = mesh.nodes[node]['real_depth'] for node in mask_cc: mask[node[0], node[1]] = 1 near_depth[node[0], node[1]] = node[2] for node in edge_cc: edge[node[0], node[1]] = 1 for node in extend_edge_cc: comp_edge[node[0], node[1]] = 1 rt_dict = {'rgb': rgb, 'disp': disp, 'depth': depth, 'real_depth': real_depth, 'self_edge': edge, 'context': context, 'mask': mask, 'fpath_map': fpath_map, 'npath_map': npath_map, 'comp_edge': comp_edge, 'valid_area': context + mask, 'near_depth': near_depth} return rt_dict def crop_maps_by_size(size, *imaps): omaps = [] for imap in imaps: omaps.append(imap[size['x_min']:size['x_max'], size['y_min']:size['y_max']].copy()) return omaps def convert2tensor(input_dict): rt_dict = {} for key, value in input_dict.items(): if 'rgb' in key or 'color' in key: rt_dict[key] = torch.FloatTensor(value).permute(2, 0, 1)[None, ...] else: rt_dict[key] = torch.FloatTensor(value)[None, None, ...] return rt_dict def filter_irrelevant_edge_new(self_edge, comp_edge, other_edges, other_edges_with_id, current_edge_id, context, depth, mesh, context_cc, spdb=False): other_edges = other_edges.squeeze().astype(np.uint8) other_edges_with_id = other_edges_with_id.squeeze() self_edge = self_edge.squeeze() dilate_bevel_self_edge = cv2.dilate((self_edge + comp_edge).astype(np.uint8), np.array([[1,1,1],[1,1,1],[1,1,1]]), iterations=1) dilate_cross_self_edge = cv2.dilate((self_edge + comp_edge).astype(np.uint8), np.array([[0,1,0],[1,1,1],[0,1,0]]).astype(np.uint8), iterations=1) edge_ids = np.unique(other_edges_with_id * context + (-1) * (1 - context)).astype(int) end_depth_maps = np.zeros_like(self_edge) self_edge_ids = np.sort(np.unique(other_edges_with_id[self_edge > 0]).astype(int)) self_edge_ids = self_edge_ids[1:] if self_edge_ids.shape[0] > 0 and self_edge_ids[0] == -1 else self_edge_ids self_comp_ids = np.sort(np.unique(other_edges_with_id[comp_edge > 0]).astype(int)) self_comp_ids = self_comp_ids[1:] if self_comp_ids.shape[0] > 0 and self_comp_ids[0] == -1 else self_comp_ids edge_ids = edge_ids[1:] if edge_ids[0] == -1 else edge_ids other_edges_info = [] extend_other_edges = np.zeros_like(other_edges) if spdb is True: f, ((ax1, ax2, ax3)) = plt.subplots(1, 3, sharex=True, sharey=True); ax1.imshow(self_edge); ax2.imshow(context); ax3.imshow(other_edges_with_id * context + (-1) * (1 - context)); plt.show() import pdb; pdb.set_trace() filter_self_edge = np.zeros_like(self_edge) for self_edge_id in self_edge_ids: filter_self_edge[other_edges_with_id == self_edge_id] = 1 dilate_self_comp_edge = cv2.dilate(comp_edge, kernel=np.ones((3, 3)), iterations=2) valid_self_comp_edge = np.zeros_like(comp_edge) for self_comp_id in self_comp_ids: valid_self_comp_edge[self_comp_id == other_edges_with_id] = 1 self_comp_edge = dilate_self_comp_edge * valid_self_comp_edge filter_self_edge = (filter_self_edge + self_comp_edge).clip(0, 1) for edge_id in edge_ids: other_edge_locs = (other_edges_with_id == edge_id).astype(np.uint8) condition = (other_edge_locs * other_edges * context.astype(np.uint8)) end_cross_point = dilate_cross_self_edge * condition * (1 - filter_self_edge) end_bevel_point = dilate_bevel_self_edge * condition * (1 - filter_self_edge) if end_bevel_point.max() != 0: end_depth_maps[end_bevel_point != 0] = depth[end_bevel_point != 0] if end_cross_point.max() == 0: nxs, nys = np.where(end_bevel_point != 0) for nx, ny in zip(nxs, nys): bevel_node = [xx for xx in context_cc if xx[0] == nx and xx[1] == ny][0] for ne in mesh.neighbors(bevel_node): if other_edges_with_id[ne[0], ne[1]] > -1 and dilate_cross_self_edge[ne[0], ne[1]] > 0: extend_other_edges[ne[0], ne[1]] = 1 break else: other_edges[other_edges_with_id == edge_id] = 0 other_edges = (other_edges + extend_other_edges).clip(0, 1) * context return other_edges, end_depth_maps, other_edges_info def require_depth_edge(context_edge, mask): dilate_mask = cv2.dilate(mask, np.array([[1,1,1],[1,1,1],[1,1,1]]).astype(np.uint8), iterations=1) if (dilate_mask * context_edge).max() == 0: return False else: return True def edge_inpainting(edge_id, context_cc, erode_context_cc, mask_cc, edge_cc, extend_edge_cc, mesh, edge_map, edge_maps_with_id, config, union_size, depth_edge_model, inpaint_iter): edge_dict = get_edge_from_nodes(context_cc, erode_context_cc, mask_cc, edge_cc, extend_edge_cc, mesh.graph['H'], mesh.graph['W'], mesh) edge_dict['edge'], end_depth_maps, _ = \ filter_irrelevant_edge_new(edge_dict['self_edge'] + edge_dict['comp_edge'], edge_map, edge_maps_with_id, edge_id, edge_dict['context'], edge_dict['depth'], mesh, context_cc | erode_context_cc, spdb=True) patch_edge_dict = dict() patch_edge_dict['mask'], patch_edge_dict['context'], patch_edge_dict['rgb'], \ patch_edge_dict['disp'], patch_edge_dict['edge'] = \ crop_maps_by_size(union_size, edge_dict['mask'], edge_dict['context'], edge_dict['rgb'], edge_dict['disp'], edge_dict['edge']) tensor_edge_dict = convert2tensor(patch_edge_dict) if require_depth_edge(patch_edge_dict['edge'], patch_edge_dict['mask']) and inpaint_iter == 0: with torch.no_grad(): device = config["gpu_ids"] if isinstance(config["gpu_ids"], int) and config["gpu_ids"] >= 0 else "cpu" depth_edge_output = depth_edge_model.forward_3P(tensor_edge_dict['mask'], tensor_edge_dict['context'], tensor_edge_dict['rgb'], tensor_edge_dict['disp'], tensor_edge_dict['edge'], unit_length=128, cuda=device) depth_edge_output = depth_edge_output.cpu() tensor_edge_dict['output'] = (depth_edge_output > config['ext_edge_threshold']).float() * tensor_edge_dict['mask'] + tensor_edge_dict['edge'] else: tensor_edge_dict['output'] = tensor_edge_dict['edge'] depth_edge_output = tensor_edge_dict['edge'] + 0 patch_edge_dict['output'] = tensor_edge_dict['output'].squeeze().data.cpu().numpy() edge_dict['output'] = np.zeros((mesh.graph['H'], mesh.graph['W'])) edge_dict['output'][union_size['x_min']:union_size['x_max'], union_size['y_min']:union_size['y_max']] = \ patch_edge_dict['output'] return edge_dict, end_depth_maps
null
6,342
import os import numpy as np import json import scipy.misc as misc import scipy.signal as signal import matplotlib.pyplot as plt import cv2 import scipy.misc as misc from skimage import io from functools import partial from vispy import scene, io from vispy.scene import visuals from functools import reduce import scipy.misc as misc from vispy.visuals.filters import Alpha import cv2 from skimage.transform import resize import copy import torch import os from inpaint.utils import refine_depth_around_edge, smooth_cntsyn_gap from inpaint.utils import require_depth_edge, filter_irrelevant_edge_new, open_small_mask from skimage.feature import canny from scipy import ndimage import time import transforms3d def resize_for_edge(tensor_dict, largest_size): resize_dict = {k: v.clone() for k, v in tensor_dict.items()} frac = largest_size / np.array([*resize_dict['edge'].shape[-2:]]).max() if frac < 1: resize_mark = torch.nn.functional.interpolate(torch.cat((resize_dict['mask'], resize_dict['context']), dim=1), scale_factor=frac, mode='bilinear') resize_dict['mask'] = (resize_mark[:, 0:1] > 0).float() resize_dict['context'] = (resize_mark[:, 1:2] == 1).float() resize_dict['context'][resize_dict['mask'] > 0] = 0 resize_dict['edge'] = torch.nn.functional.interpolate(resize_dict['edge'], scale_factor=frac, mode='bilinear') resize_dict['edge'] = (resize_dict['edge'] > 0).float() resize_dict['edge'] = resize_dict['edge'] * resize_dict['context'] resize_dict['disp'] = torch.nn.functional.interpolate(resize_dict['disp'], scale_factor=frac, mode='nearest') resize_dict['disp'] = resize_dict['disp'] * resize_dict['context'] resize_dict['rgb'] = torch.nn.functional.interpolate(resize_dict['rgb'], scale_factor=frac, mode='bilinear') resize_dict['rgb'] = resize_dict['rgb'] * resize_dict['context'] return resize_dict
null
6,343
import os import numpy as np import json import scipy.misc as misc import scipy.signal as signal import matplotlib.pyplot as plt import cv2 import scipy.misc as misc from skimage import io from functools import partial from vispy import scene, io from vispy.scene import visuals from functools import reduce import scipy.misc as misc from vispy.visuals.filters import Alpha import cv2 from skimage.transform import resize import copy import torch import os from inpaint.utils import refine_depth_around_edge, smooth_cntsyn_gap from inpaint.utils import require_depth_edge, filter_irrelevant_edge_new, open_small_mask from skimage.feature import canny from scipy import ndimage import time import transforms3d def get_map_from_nodes(nodes, height, width): omap = np.zeros((height, width)) for n in nodes: omap[n[0], n[1]] = 1 return omap
null
6,344
import os import numpy as np import json import scipy.misc as misc import scipy.signal as signal import matplotlib.pyplot as plt import cv2 import scipy.misc as misc from skimage import io from functools import partial from vispy import scene, io from vispy.scene import visuals from functools import reduce import scipy.misc as misc from vispy.visuals.filters import Alpha import cv2 from skimage.transform import resize import copy import torch import os from inpaint.utils import refine_depth_around_edge, smooth_cntsyn_gap from inpaint.utils import require_depth_edge, filter_irrelevant_edge_new, open_small_mask from skimage.feature import canny from scipy import ndimage import time import transforms3d def revise_map_by_nodes(nodes, imap, operation, limit_constr=None): assert operation == '+' or operation == '-', "Operation must be '+' (union) or '-' (exclude)" omap = copy.deepcopy(imap) revise_flag = True if operation == '+': for n in nodes: omap[n[0], n[1]] = 1 if limit_constr is not None and omap.sum() > limit_constr: omap = imap revise_flag = False elif operation == '-': for n in nodes: omap[n[0], n[1]] = 0 if limit_constr is not None and omap.sum() < limit_constr: omap = imap revise_flag = False return omap, revise_flag
null
6,345
import os import numpy as np import json import scipy.misc as misc import scipy.signal as signal import matplotlib.pyplot as plt import cv2 import scipy.misc as misc from skimage import io from functools import partial from vispy import scene, io from vispy.scene import visuals from functools import reduce import scipy.misc as misc from vispy.visuals.filters import Alpha import cv2 from skimage.transform import resize import copy import torch import os from inpaint.utils import refine_depth_around_edge, smooth_cntsyn_gap from inpaint.utils import require_depth_edge, filter_irrelevant_edge_new, open_small_mask from skimage.feature import canny from scipy import ndimage import time import transforms3d def repaint_info(mesh, cc, x_anchor, y_anchor, source_type): if source_type == 'rgb': feat = np.zeros((3, x_anchor[1] - x_anchor[0], y_anchor[1] - y_anchor[0])) else: feat = np.zeros((1, x_anchor[1] - x_anchor[0], y_anchor[1] - y_anchor[0])) for node in cc: if source_type == 'rgb': feat[:, node[0] - x_anchor[0], node[1] - y_anchor[0]] = np.array(mesh.nodes[node]['color']) / 255. elif source_type == 'd': feat[:, node[0] - x_anchor[0], node[1] - y_anchor[0]] = abs(node[2]) return feat
null
6,346
import os import numpy as np import json import scipy.misc as misc import scipy.signal as signal import matplotlib.pyplot as plt import cv2 import scipy.misc as misc from skimage import io from functools import partial from vispy import scene, io from vispy.scene import visuals from functools import reduce import scipy.misc as misc from vispy.visuals.filters import Alpha import cv2 from skimage.transform import resize import copy import torch import os from inpaint.utils import refine_depth_around_edge, smooth_cntsyn_gap from inpaint.utils import require_depth_edge, filter_irrelevant_edge_new, open_small_mask from skimage.feature import canny from scipy import ndimage import time import transforms3d def get_context_from_nodes(mesh, cc, H, W, source_type=''): if 'rgb' in source_type or 'color' in source_type: feat = np.zeros((H, W, 3)) else: feat = np.zeros((H, W)) context = np.zeros((H, W)) for node in cc: if 'rgb' in source_type or 'color' in source_type: feat[node[0], node[1]] = np.array(mesh.nodes[node]['color']) / 255. context[node[0], node[1]] = 1 else: feat[node[0], node[1]] = abs(node[2]) return feat, context
null
6,347
import os import numpy as np import json import scipy.misc as misc import scipy.signal as signal import matplotlib.pyplot as plt import cv2 import scipy.misc as misc from skimage import io from functools import partial from vispy import scene, io from vispy.scene import visuals from functools import reduce import scipy.misc as misc from vispy.visuals.filters import Alpha import cv2 from skimage.transform import resize import copy import torch import os from inpaint.utils import refine_depth_around_edge, smooth_cntsyn_gap from inpaint.utils import require_depth_edge, filter_irrelevant_edge_new, open_small_mask from skimage.feature import canny from scipy import ndimage import time import transforms3d def get_mask_from_nodes(mesh, cc, H, W): mask = np.zeros((H, W)) for node in cc: mask[node[0], node[1]] = abs(node[2]) return mask
null
6,348
import torch import torch.nn as nn import numpy as np import matplotlib.pyplot as plt import torch.nn.functional as F def weights_init(init_type='gaussian'): def init_fun(m): classname = m.__class__.__name__ if (classname.find('Conv') == 0 or classname.find( 'Linear') == 0) and hasattr(m, 'weight'): if init_type == 'gaussian': nn.init.normal_(m.weight, 0.0, 0.02) elif init_type == 'xavier': nn.init.xavier_normal_(m.weight, gain=math.sqrt(2)) elif init_type == 'kaiming': nn.init.kaiming_normal_(m.weight, a=0, mode='fan_in') elif init_type == 'orthogonal': nn.init.orthogonal_(m.weight, gain=math.sqrt(2)) elif init_type == 'default': pass else: assert 0, "Unsupported initialization: {}".format(init_type) if hasattr(m, 'bias') and m.bias is not None: nn.init.constant_(m.bias, 0.0) return init_fun
null
6,349
import torch import torch.nn as nn import numpy as np import matplotlib.pyplot as plt import torch.nn.functional as F def spectral_norm(module, mode=True): if mode: return nn.utils.spectral_norm(module) return module
null
6,350
import argparse import os import pathlib import src.misc The provided code snippet includes necessary dependencies for implementing the `maybe_chdir` function. Write a Python function `def maybe_chdir()` to solve the following problem: Detects if DepthMap was installed as a stable-diffusion-webui script, but run without current directory set to the stable-diffusion-webui root. Changes current directory if needed. This is to avoid re-downloading models and putting results into a wrong folder. Here is the function: def maybe_chdir(): """Detects if DepthMap was installed as a stable-diffusion-webui script, but run without current directory set to the stable-diffusion-webui root. Changes current directory if needed. This is to avoid re-downloading models and putting results into a wrong folder.""" try: file_path = pathlib.Path(__file__) path = file_path.parts while len(path) > 0 and path[-1] != src.misc.REPOSITORY_NAME: path = path[:-1] if len(path) >= 2 and path[-1] == src.misc.REPOSITORY_NAME and path[-2] == "extensions": path = path[:-2] listdir = os.listdir(str(pathlib.Path(*path))) if 'launch.py' in listdir and 'webui.py': os.chdir(str(pathlib.Path(*path))) except: pass
Detects if DepthMap was installed as a stable-diffusion-webui script, but run without current directory set to the stable-diffusion-webui root. Changes current directory if needed. This is to avoid re-downloading models and putting results into a wrong folder.
6,351
import gc import os.path from operator import getitem import cv2 import numpy as np import skimage.measure from PIL import Image import torch from torchvision.transforms import Compose, transforms from dmidas.dpt_depth import DPTDepthModel from dmidas.midas_net import MidasNet from dmidas.midas_net_custom import MidasNet_small from dmidas.transforms import Resize, NormalizeImage, PrepareForNet from dzoedepth.models.builder import build_model from dzoedepth.utils.config import get_config from lib.multi_depth_model_woauxi import RelDepthModel from lib.net_tools import strip_prefix_if_present from pix2pix.models.pix2pix4depth_model import Pix2Pix4DepthModel from marigold.marigold import MarigoldPipeline from pix2pix.options.test_options import TestOptions from src.misc import * from src import backbone global depthmap_device class Resize(object): """Resize sample to given size (width, height). """ def __init__( self, width, height, resize_target=True, keep_aspect_ratio=False, ensure_multiple_of=1, resize_method="lower_bound", image_interpolation_method=cv2.INTER_AREA, ): """Init. Args: width (int): desired output width height (int): desired output height resize_target (bool, optional): True: Resize the full sample (image, mask, target). False: Resize image only. Defaults to True. keep_aspect_ratio (bool, optional): True: Keep the aspect ratio of the input sample. Output sample might not have the given width and height, and resize behaviour depends on the parameter 'resize_method'. Defaults to False. ensure_multiple_of (int, optional): Output width and height is constrained to be multiple of this parameter. Defaults to 1. resize_method (str, optional): "lower_bound": Output will be at least as large as the given size. "upper_bound": Output will be at max as large as the given size. (Output size might be smaller than given size.) "minimal": Scale as least as possible. (Output size might be smaller than given size.) Defaults to "lower_bound". """ self.__width = width self.__height = height self.__resize_target = resize_target self.__keep_aspect_ratio = keep_aspect_ratio self.__multiple_of = ensure_multiple_of self.__resize_method = resize_method self.__image_interpolation_method = image_interpolation_method def constrain_to_multiple_of(self, x, min_val=0, max_val=None): y = (np.round(x / self.__multiple_of) * self.__multiple_of).astype(int) if max_val is not None and y > max_val: y = (np.floor(x / self.__multiple_of) * self.__multiple_of).astype(int) if y < min_val: y = (np.ceil(x / self.__multiple_of) * self.__multiple_of).astype(int) return y def get_size(self, width, height): # determine new height and width scale_height = self.__height / height scale_width = self.__width / width if self.__keep_aspect_ratio: if self.__resize_method == "lower_bound": # scale such that output size is lower bound if scale_width > scale_height: # fit width scale_height = scale_width else: # fit height scale_width = scale_height elif self.__resize_method == "upper_bound": # scale such that output size is upper bound if scale_width < scale_height: # fit width scale_height = scale_width else: # fit height scale_width = scale_height elif self.__resize_method == "minimal": # scale as least as possbile if abs(1 - scale_width) < abs(1 - scale_height): # fit width scale_height = scale_width else: # fit height scale_width = scale_height else: raise ValueError( f"resize_method {self.__resize_method} not implemented" ) if self.__resize_method == "lower_bound": new_height = self.constrain_to_multiple_of( scale_height * height, min_val=self.__height ) new_width = self.constrain_to_multiple_of( scale_width * width, min_val=self.__width ) elif self.__resize_method == "upper_bound": new_height = self.constrain_to_multiple_of( scale_height * height, max_val=self.__height ) new_width = self.constrain_to_multiple_of( scale_width * width, max_val=self.__width ) elif self.__resize_method == "minimal": new_height = self.constrain_to_multiple_of(scale_height * height) new_width = self.constrain_to_multiple_of(scale_width * width) else: raise ValueError(f"resize_method {self.__resize_method} not implemented") return (new_width, new_height) def __call__(self, sample): width, height = self.get_size( sample["image"].shape[1], sample["image"].shape[0] ) # resize sample sample["image"] = cv2.resize( sample["image"], (width, height), interpolation=self.__image_interpolation_method, ) if self.__resize_target: if "disparity" in sample: sample["disparity"] = cv2.resize( sample["disparity"], (width, height), interpolation=cv2.INTER_NEAREST, ) if "depth" in sample: sample["depth"] = cv2.resize( sample["depth"], (width, height), interpolation=cv2.INTER_NEAREST ) sample["mask"] = cv2.resize( sample["mask"].astype(np.float32), (width, height), interpolation=cv2.INTER_NEAREST, ) sample["mask"] = sample["mask"].astype(bool) return sample class PrepareForNet(object): """Prepare sample for usage as network input. """ def __init__(self): pass def __call__(self, sample): image = np.transpose(sample["image"], (2, 0, 1)) sample["image"] = np.ascontiguousarray(image).astype(np.float32) if "mask" in sample: sample["mask"] = sample["mask"].astype(np.float32) sample["mask"] = np.ascontiguousarray(sample["mask"]) if "disparity" in sample: disparity = sample["disparity"].astype(np.float32) sample["disparity"] = np.ascontiguousarray(disparity) if "depth" in sample: depth = sample["depth"].astype(np.float32) sample["depth"] = np.ascontiguousarray(depth) return sample def estimatemidas(img, model, w, h, resize_mode, normalization, no_half, precision_is_autocast): import contextlib # init transform transform = Compose( [ Resize( w, h, resize_target=None, keep_aspect_ratio=True, ensure_multiple_of=32, resize_method=resize_mode, image_interpolation_method=cv2.INTER_CUBIC, ), normalization, PrepareForNet(), ] ) # transform input img_input = transform({"image": img})["image"] # compute precision_scope = torch.autocast if precision_is_autocast and depthmap_device == torch.device( "cuda") else contextlib.nullcontext with torch.no_grad(), precision_scope("cuda"): sample = torch.from_numpy(img_input).to(depthmap_device).unsqueeze(0) if depthmap_device == torch.device("cuda"): sample = sample.to(memory_format=torch.channels_last) if not no_half: sample = sample.half() prediction = model.forward(sample) prediction = ( torch.nn.functional.interpolate( prediction.unsqueeze(1), size=img.shape[:2], mode="bicubic", align_corners=False, ) .squeeze() .cpu() .numpy() ) return prediction
null
6,352
import gc import os.path from operator import getitem import cv2 import numpy as np import skimage.measure from PIL import Image import torch from torchvision.transforms import Compose, transforms from dmidas.dpt_depth import DPTDepthModel from dmidas.midas_net import MidasNet from dmidas.midas_net_custom import MidasNet_small from dmidas.transforms import Resize, NormalizeImage, PrepareForNet from dzoedepth.models.builder import build_model from dzoedepth.utils.config import get_config from lib.multi_depth_model_woauxi import RelDepthModel from lib.net_tools import strip_prefix_if_present from pix2pix.models.pix2pix4depth_model import Pix2Pix4DepthModel from marigold.marigold import MarigoldPipeline from pix2pix.options.test_options import TestOptions from src.misc import * from src import backbone def impatch(image, rect): # Extract the given patch pixels from a given image. w1 = rect[0] h1 = rect[1] w2 = w1 + rect[2] h2 = h1 + rect[3] image_patch = image[h1:h2, w1:w2] return image_patch
null
6,353
import gc import os.path from operator import getitem import cv2 import numpy as np import skimage.measure from PIL import Image import torch from torchvision.transforms import Compose, transforms from dmidas.dpt_depth import DPTDepthModel from dmidas.midas_net import MidasNet from dmidas.midas_net_custom import MidasNet_small from dmidas.transforms import Resize, NormalizeImage, PrepareForNet from dzoedepth.models.builder import build_model from dzoedepth.utils.config import get_config from lib.multi_depth_model_woauxi import RelDepthModel from lib.net_tools import strip_prefix_if_present from pix2pix.models.pix2pix4depth_model import Pix2Pix4DepthModel from marigold.marigold import MarigoldPipeline from pix2pix.options.test_options import TestOptions from src.misc import * from src import backbone class ImageandPatchs: def __init__(self, root_dir, name, patchsinfo, rgb_image, scale=1): self.root_dir = root_dir self.patchsinfo = patchsinfo self.name = name self.patchs = patchsinfo self.scale = scale self.rgb_image = cv2.resize(rgb_image, (round(rgb_image.shape[1] * scale), round(rgb_image.shape[0] * scale)), interpolation=cv2.INTER_CUBIC) self.do_have_estimate = False self.estimation_updated_image = None self.estimation_base_image = None def __len__(self): return len(self.patchs) def set_base_estimate(self, est): self.estimation_base_image = est if self.estimation_updated_image is not None: self.do_have_estimate = True def set_updated_estimate(self, est): self.estimation_updated_image = est if self.estimation_base_image is not None: self.do_have_estimate = True def __getitem__(self, index): patch_id = int(self.patchs[index][0]) rect = np.array(self.patchs[index][1]['rect']) msize = self.patchs[index][1]['size'] ## applying scale to rect: rect = np.round(rect * self.scale) rect = rect.astype('int') msize = round(msize * self.scale) patch_rgb = impatch(self.rgb_image, rect) if self.do_have_estimate: patch_whole_estimate_base = impatch(self.estimation_base_image, rect) patch_whole_estimate_updated = impatch(self.estimation_updated_image, rect) return {'patch_rgb': patch_rgb, 'patch_whole_estimate_base': patch_whole_estimate_base, 'patch_whole_estimate_updated': patch_whole_estimate_updated, 'rect': rect, 'size': msize, 'id': patch_id} else: return {'patch_rgb': patch_rgb, 'rect': rect, 'size': msize, 'id': patch_id} def print_options(self, opt): """Print and save options It will print both current options and default values(if different). It will save options into a text file / [checkpoints_dir] / opt.txt """ message = '' message += '----------------- Options ---------------\n' for k, v in sorted(vars(opt).items()): comment = '' default = self.parser.get_default(k) if v != default: comment = '\t[default: %s]' % str(default) message += '{:>25}: {:<30}{}\n'.format(str(k), str(v), comment) message += '----------------- End -------------------' print(message) # save to the disk """ expr_dir = os.path.join(opt.checkpoints_dir, opt.name) util.mkdirs(expr_dir) file_name = os.path.join(expr_dir, '{}_opt.txt'.format(opt.phase)) with open(file_name, 'wt') as opt_file: opt_file.write(message) opt_file.write('\n') """ def parse(self): """Parse our options, create checkpoints directory suffix, and set up gpu device.""" opt = self.gather_options() opt.isTrain = self.isTrain # train or test # process opt.suffix if opt.suffix: suffix = ('_' + opt.suffix.format(**vars(opt))) if opt.suffix != '' else '' opt.name = opt.name + suffix # self.print_options(opt) # set gpu ids str_ids = opt.gpu_ids.split(',') opt.gpu_ids = [] for str_id in str_ids: id = int(str_id) if id >= 0: opt.gpu_ids.append(id) # if len(opt.gpu_ids) > 0: # torch.cuda.set_device(opt.gpu_ids[0]) self.opt = opt return self.opt class ImageandPatchs: def __init__(self, root_dir, name, patchsinfo, rgb_image, scale=1): self.root_dir = root_dir self.patchsinfo = patchsinfo self.name = name self.patchs = patchsinfo self.scale = scale self.rgb_image = cv2.resize(rgb_image, (round(rgb_image.shape[1] * scale), round(rgb_image.shape[0] * scale)), interpolation=cv2.INTER_CUBIC) self.do_have_estimate = False self.estimation_updated_image = None self.estimation_base_image = None def __len__(self): return len(self.patchs) def set_base_estimate(self, est): self.estimation_base_image = est if self.estimation_updated_image is not None: self.do_have_estimate = True def set_updated_estimate(self, est): self.estimation_updated_image = est if self.estimation_base_image is not None: self.do_have_estimate = True def __getitem__(self, index): patch_id = int(self.patchs[index][0]) rect = np.array(self.patchs[index][1]['rect']) msize = self.patchs[index][1]['size'] ## applying scale to rect: rect = np.round(rect * self.scale) rect = rect.astype('int') msize = round(msize * self.scale) patch_rgb = impatch(self.rgb_image, rect) if self.do_have_estimate: patch_whole_estimate_base = impatch(self.estimation_base_image, rect) patch_whole_estimate_updated = impatch(self.estimation_updated_image, rect) return {'patch_rgb': patch_rgb, 'patch_whole_estimate_base': patch_whole_estimate_base, 'patch_whole_estimate_updated': patch_whole_estimate_updated, 'rect': rect, 'size': msize, 'id': patch_id} else: return {'patch_rgb': patch_rgb, 'rect': rect, 'size': msize, 'id': patch_id} def print_options(self, opt): """Print and save options It will print both current options and default values(if different). It will save options into a text file / [checkpoints_dir] / opt.txt """ message = '' message += '----------------- Options ---------------\n' for k, v in sorted(vars(opt).items()): comment = '' default = self.parser.get_default(k) if v != default: comment = '\t[default: %s]' % str(default) message += '{:>25}: {:<30}{}\n'.format(str(k), str(v), comment) message += '----------------- End -------------------' print(message) # save to the disk """ expr_dir = os.path.join(opt.checkpoints_dir, opt.name) util.mkdirs(expr_dir) file_name = os.path.join(expr_dir, '{}_opt.txt'.format(opt.phase)) with open(file_name, 'wt') as opt_file: opt_file.write(message) opt_file.write('\n') """ def parse(self): """Parse our options, create checkpoints directory suffix, and set up gpu device.""" opt = self.gather_options() opt.isTrain = self.isTrain # train or test # process opt.suffix if opt.suffix: suffix = ('_' + opt.suffix.format(**vars(opt))) if opt.suffix != '' else '' opt.name = opt.name + suffix # self.print_options(opt) # set gpu ids str_ids = opt.gpu_ids.split(',') opt.gpu_ids = [] for str_id in str_ids: id = int(str_id) if id >= 0: opt.gpu_ids.append(id) # if len(opt.gpu_ids) > 0: # torch.cuda.set_device(opt.gpu_ids[0]) self.opt = opt return self.opt def generatemask(size): # Generates a Guassian mask mask = np.zeros(size, dtype=np.float32) sigma = int(size[0] / 16) k_size = int(2 * np.ceil(2 * int(size[0] / 16)) + 1) mask[int(0.15 * size[0]):size[0] - int(0.15 * size[0]), int(0.15 * size[1]): size[1] - int(0.15 * size[1])] = 1 mask = cv2.GaussianBlur(mask, (int(k_size), int(k_size)), sigma) mask = (mask - mask.min()) / (mask.max() - mask.min()) mask = mask.astype(np.float32) return mask def calculateprocessingres(img, basesize, confidence=0.1, scale_threshold=3, whole_size_threshold=3000): # Returns the R_x resolution described in section 5 of the main paper. # Parameters: # img :input rgb image # basesize : size the dilation kernel which is equal to receptive field of the network. # confidence: value of x in R_x; allowed percentage of pixels that are not getting any contextual cue. # scale_threshold: maximum allowed upscaling on the input image ; it has been set to 3. # whole_size_threshold: maximum allowed resolution. (R_max from section 6 of the main paper) # Returns: # outputsize_scale*speed_scale :The computed R_x resolution # patch_scale: K parameter from section 6 of the paper # speed scale parameter is to process every image in a smaller size to accelerate the R_x resolution search speed_scale = 32 image_dim = int(min(img.shape[0:2])) gray = rgb2gray(img) grad = np.abs(cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=3)) + np.abs(cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=3)) grad = cv2.resize(grad, (image_dim, image_dim), cv2.INTER_AREA) # thresholding the gradient map to generate the edge-map as a proxy of the contextual cues m = grad.min() M = grad.max() middle = m + (0.4 * (M - m)) grad[grad < middle] = 0 grad[grad >= middle] = 1 # dilation kernel with size of the receptive field kernel = np.ones((int(basesize / speed_scale), int(basesize / speed_scale)), float) # dilation kernel with size of the a quarter of receptive field used to compute k # as described in section 6 of main paper kernel2 = np.ones((int(basesize / (4 * speed_scale)), int(basesize / (4 * speed_scale))), float) # Output resolution limit set by the whole_size_threshold and scale_threshold. threshold = min(whole_size_threshold, scale_threshold * max(img.shape[:2])) outputsize_scale = basesize / speed_scale for p_size in range(int(basesize / speed_scale), int(threshold / speed_scale), int(basesize / (2 * speed_scale))): grad_resized = resizewithpool(grad, p_size) grad_resized = cv2.resize(grad_resized, (p_size, p_size), cv2.INTER_NEAREST) grad_resized[grad_resized >= 0.5] = 1 grad_resized[grad_resized < 0.5] = 0 dilated = cv2.dilate(grad_resized, kernel, iterations=1) meanvalue = (1 - dilated).mean() if meanvalue > confidence: break else: outputsize_scale = p_size grad_region = cv2.dilate(grad_resized, kernel2, iterations=1) patch_scale = grad_region.mean() return int(outputsize_scale * speed_scale), patch_scale def doubleestimate(img, size1, size2, pix2pixsize, model, net_type, pix2pixmodel): # Generate the low resolution estimation estimate1 = singleestimate(img, size1, model, net_type) # Resize to the inference size of merge network. estimate1 = cv2.resize(estimate1, (pix2pixsize, pix2pixsize), interpolation=cv2.INTER_CUBIC) # Generate the high resolution estimation estimate2 = singleestimate(img, size2, model, net_type) # Resize to the inference size of merge network. estimate2 = cv2.resize(estimate2, (pix2pixsize, pix2pixsize), interpolation=cv2.INTER_CUBIC) # Inference on the merge model pix2pixmodel.set_input(estimate1, estimate2) pix2pixmodel.test() visuals = pix2pixmodel.get_current_visuals() prediction_mapped = visuals['fake_B'] prediction_mapped = (prediction_mapped + 1) / 2 prediction_mapped = (prediction_mapped - torch.min(prediction_mapped)) / ( torch.max(prediction_mapped) - torch.min(prediction_mapped)) prediction_mapped = prediction_mapped.squeeze().cpu().numpy() return prediction_mapped def generatepatchs(img, base_size, factor): # Compute the gradients as a proxy of the contextual cues. img_gray = rgb2gray(img) whole_grad = np.abs(cv2.Sobel(img_gray, cv2.CV_64F, 0, 1, ksize=3)) + \ np.abs(cv2.Sobel(img_gray, cv2.CV_64F, 1, 0, ksize=3)) threshold = whole_grad[whole_grad > 0].mean() whole_grad[whole_grad < threshold] = 0 # We use the integral image to speed-up the evaluation of the amount of gradients for each patch. gf = whole_grad.sum() / len(whole_grad.reshape(-1)) grad_integral_image = cv2.integral(whole_grad) # Variables are selected such that the initial patch size would be the receptive field size # and the stride is set to 1/3 of the receptive field size. blsize = int(round(base_size / 2)) stride = int(round(blsize * 0.75)) # Get initial Grid patch_bound_list = applyGridpatch(blsize, stride, img, [0, 0, 0, 0]) # Refine initial Grid of patches by discarding the flat (in terms of gradients of the rgb image) ones. Refine # each patch size to ensure that there will be enough depth cues for the network to generate a consistent depth map. print("Selecting patches ...") patch_bound_list = adaptiveselection(grad_integral_image, patch_bound_list, gf, factor) # Sort the patch list to make sure the merging operation will be done with the correct order: starting from biggest # patch patchset = sorted(patch_bound_list.items(), key=lambda x: getitem(x[1], 'size'), reverse=True) return patchset The provided code snippet includes necessary dependencies for implementing the `estimateboost` function. Write a Python function `def estimateboost(img, model, model_type, pix2pixmodel, whole_size_threshold)` to solve the following problem: # recompute a, b and saturate to max res. if max(a,b) > max_res: print('Default Res is higher than max-res: Reducing final resolution') if img.shape[0] > img.shape[1]: a = max_res b = round(option.max_res * img.shape[1] / img.shape[0]) else: a = round(option.max_res * img.shape[0] / img.shape[1]) b = max_res b = int(b) a = int(a) Here is the function: def estimateboost(img, model, model_type, pix2pixmodel, whole_size_threshold): pix2pixsize = 1024 # TODO: pix2pixsize and whole_size_threshold to setting? if model_type == 0: # leres net_receptive_field_size = 448 elif model_type == 1: # dpt_beit_large_512 net_receptive_field_size = 512 elif model_type == 11: # depth_anything net_receptive_field_size = 518 else: # other midas # TODO Marigold support net_receptive_field_size = 384 patch_netsize = 2 * net_receptive_field_size # Good luck trying to use zoedepth gc.collect() backbone.torch_gc() # Generate mask used to smoothly blend the local pathc estimations to the base estimate. # It is arbitrarily large to avoid artifacts during rescaling for each crop. mask_org = generatemask((3000, 3000)) mask = mask_org.copy() # Value x of R_x defined in the section 5 of the main paper. r_threshold_value = 0.2 # if R0: # r_threshold_value = 0 input_resolution = img.shape scale_threshold = 3 # Allows up-scaling with a scale up to 3 # Find the best input resolution R-x. The resolution search described in section 5-double estimation of the main paper and section B of the # supplementary material. whole_image_optimal_size, patch_scale = calculateprocessingres(img, net_receptive_field_size, r_threshold_value, scale_threshold, whole_size_threshold) print('wholeImage being processed in :', whole_image_optimal_size) # Generate the base estimate using the double estimation. whole_estimate = doubleestimate(img, net_receptive_field_size, whole_image_optimal_size, pix2pixsize, model, model_type, pix2pixmodel) # Compute the multiplier described in section 6 of the main paper to make sure our initial patch can select # small high-density regions of the image. factor = max(min(1, 4 * patch_scale * whole_image_optimal_size / whole_size_threshold), 0.2) print('Adjust factor is:', 1 / factor) # Compute the default target resolution. if img.shape[0] > img.shape[1]: a = 2 * whole_image_optimal_size b = round(2 * whole_image_optimal_size * img.shape[1] / img.shape[0]) else: a = round(2 * whole_image_optimal_size * img.shape[0] / img.shape[1]) b = 2 * whole_image_optimal_size b = int(round(b / factor)) a = int(round(a / factor)) """ # recompute a, b and saturate to max res. if max(a,b) > max_res: print('Default Res is higher than max-res: Reducing final resolution') if img.shape[0] > img.shape[1]: a = max_res b = round(option.max_res * img.shape[1] / img.shape[0]) else: a = round(option.max_res * img.shape[0] / img.shape[1]) b = max_res b = int(b) a = int(a) """ img = cv2.resize(img, (b, a), interpolation=cv2.INTER_CUBIC) # Extract selected patches for local refinement base_size = net_receptive_field_size * 2 patchset = generatepatchs(img, base_size, factor) print('Target resolution: ', img.shape) # Computing a scale in case user prompted to generate the results as the same resolution of the input. # Notice that our method output resolution is independent of the input resolution and this parameter will only # enable a scaling operation during the local patch merge implementation to generate results with the same resolution # as the input. """ if output_resolution == 1: mergein_scale = input_resolution[0] / img.shape[0] print('Dynamicly change merged-in resolution; scale:', mergein_scale) else: mergein_scale = 1 """ # always rescale to input res for now mergein_scale = input_resolution[0] / img.shape[0] imageandpatchs = ImageandPatchs('', '', patchset, img, mergein_scale) whole_estimate_resized = cv2.resize(whole_estimate, (round(img.shape[1] * mergein_scale), round(img.shape[0] * mergein_scale)), interpolation=cv2.INTER_CUBIC) imageandpatchs.set_base_estimate(whole_estimate_resized.copy()) imageandpatchs.set_updated_estimate(whole_estimate_resized.copy()) print('Resulting depthmap resolution will be :', whole_estimate_resized.shape[:2]) print('patches to process: ' + str(len(imageandpatchs))) # Enumerate through all patches, generate their estimations and refining the base estimate. for patch_ind in range(len(imageandpatchs)): # Get patch information patch = imageandpatchs[patch_ind] # patch object patch_rgb = patch['patch_rgb'] # rgb patch patch_whole_estimate_base = patch['patch_whole_estimate_base'] # corresponding patch from base rect = patch['rect'] # patch size and location patch_id = patch['id'] # patch ID org_size = patch_whole_estimate_base.shape # the original size from the unscaled input print('\t processing patch', patch_ind, '/', len(imageandpatchs) - 1, '|', rect) # We apply double estimation for patches. The high resolution value is fixed to twice the receptive # field size of the network for patches to accelerate the process. patch_estimation = doubleestimate(patch_rgb, net_receptive_field_size, patch_netsize, pix2pixsize, model, model_type, pix2pixmodel) patch_estimation = cv2.resize(patch_estimation, (pix2pixsize, pix2pixsize), interpolation=cv2.INTER_CUBIC) patch_whole_estimate_base = cv2.resize(patch_whole_estimate_base, (pix2pixsize, pix2pixsize), interpolation=cv2.INTER_CUBIC) # Merging the patch estimation into the base estimate using our merge network: # We feed the patch estimation and the same region from the updated base estimate to the merge network # to generate the target estimate for the corresponding region. pix2pixmodel.set_input(patch_whole_estimate_base, patch_estimation) # Run merging network pix2pixmodel.test() visuals = pix2pixmodel.get_current_visuals() prediction_mapped = visuals['fake_B'] prediction_mapped = (prediction_mapped + 1) / 2 prediction_mapped = prediction_mapped.squeeze().cpu().numpy() mapped = prediction_mapped # We use a simple linear polynomial to make sure the result of the merge network would match the values of # base estimate p_coef = np.polyfit(mapped.reshape(-1), patch_whole_estimate_base.reshape(-1), deg=1) merged = np.polyval(p_coef, mapped.reshape(-1)).reshape(mapped.shape) merged = cv2.resize(merged, (org_size[1], org_size[0]), interpolation=cv2.INTER_CUBIC) # Get patch size and location w1 = rect[0] h1 = rect[1] w2 = w1 + rect[2] h2 = h1 + rect[3] # To speed up the implementation, we only generate the Gaussian mask once with a sufficiently large size # and resize it to our needed size while merging the patches. if mask.shape != org_size: mask = cv2.resize(mask_org, (org_size[1], org_size[0]), interpolation=cv2.INTER_LINEAR) tobemergedto = imageandpatchs.estimation_updated_image # Update the whole estimation: # We use a simple Gaussian mask to blend the merged patch region with the base estimate to ensure seamless # blending at the boundaries of the patch region. tobemergedto[h1:h2, w1:w2] = np.multiply(tobemergedto[h1:h2, w1:w2], 1 - mask) + np.multiply(merged, mask) imageandpatchs.set_updated_estimate(tobemergedto) # output return cv2.resize(imageandpatchs.estimation_updated_image, (input_resolution[1], input_resolution[0]), interpolation=cv2.INTER_CUBIC)
# recompute a, b and saturate to max res. if max(a,b) > max_res: print('Default Res is higher than max-res: Reducing final resolution') if img.shape[0] > img.shape[1]: a = max_res b = round(option.max_res * img.shape[1] / img.shape[0]) else: a = round(option.max_res * img.shape[0] / img.shape[1]) b = max_res b = int(b) a = int(a)
6,354
import numpy as np from PIL import Image def njit(parallel=False): def Inner(func): return lambda *args, **kwargs: func(*args, **kwargs) return Inner
null
6,355
import traceback from pathlib import Path import gradio as gr from PIL import Image from src import backbone, video_mode from src.core import core_generation_funnel, unload_models, run_makevideo from src.depthmap_generation import ModelHolder from src.gradio_args_transport import GradioComponentBundle from src.misc import * from src.common_constants import GenerationOptions as go def ensure_gradio_temp_directory(): try: import tempfile path = os.path.join(tempfile.gettempdir(), 'gradio') if not (os.path.exists(path)): os.mkdir(path) except Exception as e: traceback.print_exc()
null
6,356
import traceback from pathlib import Path import gradio as gr from PIL import Image from src import backbone, video_mode from src.core import core_generation_funnel, unload_models, run_makevideo from src.depthmap_generation import ModelHolder from src.gradio_args_transport import GradioComponentBundle from src.misc import * from src.common_constants import GenerationOptions as go def main_ui_panel(is_depth_tab): def open_folder_action(): def depthmap_mode_video(inp): custom_css = """ #depthmap_vm_input {height: 75px} #depthmap_vm_custom {height: 75px} """ def run_generate(*inputs): def run_makevideo(fn_mesh, vid_numframes, vid_fps, vid_traj, vid_shift, vid_border, dolly, vid_format, vid_ssaa, outpath=None, basename=None): def unload_models(): class GradioComponentBundle: def __init__(self): def _raw_assignment(self, key, value, ignored=False): def _append_el(self, thing, ignored=False): def __iadd__(self, els): def __isub__(self, els): def __ior__(self, thing): def __getitem__(self, key): def __contains__(self, key): def enkey_tail(self): def enkey_body(self): def add_rule(self, first, rule, second): def enkey_to_dict(inp): def on_ui_tabs(): inp = GradioComponentBundle() with gr.Blocks(analytics_enabled=False, title="DepthMap", css=custom_css) as depthmap_interface: with gr.Row(equal_height=False): with gr.Column(variant='panel'): inp += 'depthmap_mode', gr.HTML(visible=False, value='0') with gr.Tabs(): with gr.TabItem('Single Image') as depthmap_mode_0: with gr.Group(): with gr.Row(): inp += gr.Image(label="Source", source="upload", interactive=True, type="pil", elem_id="depthmap_input_image") # TODO: depthmap generation settings should disappear when using this inp += gr.File(label="Custom DepthMap", file_count="single", interactive=True, type="file", elem_id='custom_depthmap_img', visible=False) inp += gr.Checkbox(elem_id="custom_depthmap", label="Use custom DepthMap", value=False) with gr.TabItem('Batch Process') as depthmap_mode_1: inp += gr.File(elem_id='image_batch', label="Batch Process", file_count="multiple", interactive=True, type="file") with gr.TabItem('Batch from Directory') as depthmap_mode_2: inp += gr.Textbox(elem_id="depthmap_batch_input_dir", label="Input directory", **backbone.get_hide_dirs(), placeholder="A directory on the same machine where the server is running.") inp += gr.Textbox(elem_id="depthmap_batch_output_dir", label="Output directory", **backbone.get_hide_dirs(), placeholder="Leave blank to save images to the default path.") gr.HTML("Files in the output directory may be overwritten.") inp += gr.Checkbox(elem_id="depthmap_batch_reuse", label="Skip generation and use (edited/custom) depthmaps " "in output directory when a file already exists.", value=True) with gr.TabItem('Single Video') as depthmap_mode_3: inp = depthmap_mode_video(inp) submit = gr.Button('Generate', elem_id="depthmap_generate", variant='primary') inp |= main_ui_panel(True) # Main panel is inserted here unloadmodels = gr.Button('Unload models', elem_id="depthmap_unloadmodels") with gr.Column(variant='panel'): with gr.Tabs(elem_id="mode_depthmap_output"): with gr.TabItem('Depth Output'): with gr.Group(): result_images = gr.Gallery(label='Output', show_label=False, elem_id=f"depthmap_gallery", columns=4) with gr.Column(): html_info = gr.HTML() folder_symbol = '\U0001f4c2' # 📂 gr.Button(folder_symbol, visible=not backbone.get_cmd_opt('hide_ui_dir_config', False)).click( fn=lambda: open_folder_action(), inputs=[], outputs=[], ) with gr.TabItem('3D Mesh'): with gr.Group(): result_depthmesh = gr.Model3D(label="3d Mesh", clear_color=[1.0, 1.0, 1.0, 1.0]) with gr.Row(): # loadmesh = gr.Button('Load') clearmesh = gr.Button('Clear') with gr.TabItem('Generate video'): # generate video with gr.Group(): with gr.Row(): gr.Markdown("Generate video from inpainted(!) mesh.") with gr.Row(): depth_vid = gr.Video(interactive=False) with gr.Column(): vid_html_info_x = gr.HTML() vid_html_info = gr.HTML() fn_mesh = gr.Textbox(label="Input Mesh (.ply | .obj)", **backbone.get_hide_dirs(), placeholder="A file on the same machine where " "the server is running.") with gr.Row(): vid_numframes = gr.Textbox(label="Number of frames", value="300") vid_fps = gr.Textbox(label="Framerate", value="40") vid_format = gr.Dropdown(label="Format", choices=['mp4', 'webm'], value='mp4', type="value", elem_id="video_format") vid_ssaa = gr.Dropdown(label="SSAA", choices=['1', '2', '3', '4'], value='3', type="value", elem_id="video_ssaa") with gr.Row(): vid_traj = gr.Dropdown(label="Trajectory", choices=['straight-line', 'double-straight-line', 'circle'], value='double-straight-line', type="index", elem_id="video_trajectory") vid_shift = gr.Textbox(label="Translate: x, y, z", value="-0.015, 0.0, -0.05") vid_border = gr.Textbox(label="Crop: top, left, bottom, right", value="0.03, 0.03, 0.05, 0.03") vid_dolly = gr.Checkbox(label="Dolly", value=False, elem_classes="smalltxt") with gr.Row(): submit_vid = gr.Button('Generate Video', elem_id="depthmap_generatevideo", variant='primary') inp += inp.enkey_tail() depthmap_mode_0.select(lambda: '0', None, inp['depthmap_mode']) depthmap_mode_1.select(lambda: '1', None, inp['depthmap_mode']) depthmap_mode_2.select(lambda: '2', None, inp['depthmap_mode']) depthmap_mode_3.select(lambda: '3', None, inp['depthmap_mode']) def custom_depthmap_change_fn(mode, zero_on, three_on): hide = mode == '0' and zero_on or mode == '3' and three_on return inp['custom_depthmap_img'].update(visible=hide), \ inp['depthmap_gen_row_0'].update(visible=not hide), \ inp['depthmap_gen_row_1'].update(visible=not hide), \ inp['depthmap_gen_row_3'].update(visible=not hide), not hide custom_depthmap_change_els = ['depthmap_mode', 'custom_depthmap', 'depthmap_vm_custom_checkbox'] for el in custom_depthmap_change_els: inp[el].change( fn=custom_depthmap_change_fn, inputs=[inp[el] for el in custom_depthmap_change_els], outputs=[inp[st] for st in [ 'custom_depthmap_img', 'depthmap_gen_row_0', 'depthmap_gen_row_1', 'depthmap_gen_row_3', go.DO_OUTPUT_DEPTH]]) unloadmodels.click( fn=unload_models, inputs=[], outputs=[] ) clearmesh.click( fn=lambda: None, inputs=[], outputs=[result_depthmesh] ) submit.click( fn=backbone.wrap_gradio_gpu_call(run_generate), inputs=inp.enkey_body(), outputs=[ result_images, fn_mesh, result_depthmesh, html_info ] ) submit_vid.click( fn=backbone.wrap_gradio_gpu_call(run_makevideo), inputs=[ fn_mesh, vid_numframes, vid_fps, vid_traj, vid_shift, vid_border, vid_dolly, vid_format, vid_ssaa ], outputs=[ depth_vid, vid_html_info_x, vid_html_info ] ) return depthmap_interface
null
6,357
import subprocess import os import pathlib import builtins def get_commit_hash(): try: file_path = pathlib.Path(__file__).parent return subprocess.check_output( [os.environ.get("GIT", "git"), "rev-parse", "HEAD"], cwd=file_path, shell=False, stderr=subprocess.DEVNULL, encoding='utf8').strip()[0:8] except Exception: return "<none>"
null
6,358
import subprocess import os import pathlib import builtins def ensure_file_downloaded(filename, url, sha256_hash_prefix=None): import torch # Do not check the hash every time - it is somewhat time-consumin if os.path.exists(filename): return if type(url) is not list: url = [url] for cur_url in url: try: print("Downloading", cur_url, "to", filename) torch.hub.download_url_to_file(cur_url, filename, sha256_hash_prefix) if os.path.exists(filename): return # The correct model was downloaded, no need to try more except: pass raise RuntimeError('Download failed. Try again later or manually download the file to that location.')
null
6,359
import torchsparse.nn.functional as spf from torchsparse.point_tensor import PointTensor from torchsparse.utils.kernel_region import * from torchsparse.utils.helpers import * def initial_voxelize(z, init_res, after_res): new_float_coord = torch.cat( [(z.C[:, :3] * init_res) / after_res, z.C[:, -1].view(-1, 1)], 1) pc_hash = spf.sphash(torch.floor(new_float_coord).int()) sparse_hash = torch.unique(pc_hash) idx_query = spf.sphashquery(pc_hash, sparse_hash) counts = spf.spcount(idx_query.int(), len(sparse_hash)) inserted_coords = spf.spvoxelize(torch.floor(new_float_coord), idx_query, counts) inserted_coords = torch.round(inserted_coords).int() inserted_feat = spf.spvoxelize(z.F, idx_query, counts) new_tensor = SparseTensor(inserted_feat, inserted_coords, 1) new_tensor.check() z.additional_features['idx_query'][1] = idx_query z.additional_features['counts'][1] = counts z.C = new_float_coord return new_tensor
null
6,360
import torchsparse.nn.functional as spf from torchsparse.point_tensor import PointTensor from torchsparse.utils.kernel_region import * from torchsparse.utils.helpers import * def point_to_voxel(x, z): if z.additional_features is None or z.additional_features.get('idx_query') is None\ or z.additional_features['idx_query'].get(x.s) is None: #pc_hash = hash_gpu(torch.floor(z.C).int()) pc_hash = spf.sphash( torch.cat([ torch.floor(z.C[:, :3] / x.s).int() * x.s, z.C[:, -1].int().view(-1, 1) ], 1)) sparse_hash = spf.sphash(x.C) idx_query = spf.sphashquery(pc_hash, sparse_hash) counts = spf.spcount(idx_query.int(), x.C.shape[0]) z.additional_features['idx_query'][x.s] = idx_query z.additional_features['counts'][x.s] = counts else: idx_query = z.additional_features['idx_query'][x.s] counts = z.additional_features['counts'][x.s] inserted_feat = spf.spvoxelize(z.F, idx_query, counts) new_tensor = SparseTensor(inserted_feat, x.C, x.s) new_tensor.coord_maps = x.coord_maps new_tensor.kernel_maps = x.kernel_maps return new_tensor
null
6,361
import torchsparse.nn.functional as spf from torchsparse.point_tensor import PointTensor from torchsparse.utils.kernel_region import * from torchsparse.utils.helpers import * def voxel_to_point(x, z, nearest=False): if z.idx_query is None or z.weights is None or z.idx_query.get( x.s) is None or z.weights.get(x.s) is None: kr = KernelRegion(2, x.s, 1) off = kr.get_kernel_offset().to(z.F.device) #old_hash = kernel_hash_gpu(torch.floor(z.C).int(), off) old_hash = spf.sphash( torch.cat([ torch.floor(z.C[:, :3] / x.s).int() * x.s, z.C[:, -1].int().view(-1, 1) ], 1), off) pc_hash = spf.sphash(x.C.to(z.F.device)) idx_query = spf.sphashquery(old_hash, pc_hash) weights = spf.calc_ti_weights(z.C, idx_query, scale=x.s).transpose(0, 1).contiguous() idx_query = idx_query.transpose(0, 1).contiguous() if nearest: weights[:, 1:] = 0. idx_query[:, 1:] = -1 new_feat = spf.spdevoxelize(x.F, idx_query, weights) new_tensor = PointTensor(new_feat, z.C, idx_query=z.idx_query, weights=z.weights) new_tensor.additional_features = z.additional_features new_tensor.idx_query[x.s] = idx_query new_tensor.weights[x.s] = weights z.idx_query[x.s] = idx_query z.weights[x.s] = weights else: new_feat = spf.spdevoxelize(x.F, z.idx_query.get(x.s), z.weights.get(x.s)) new_tensor = PointTensor(new_feat, z.C, idx_query=z.idx_query, weights=z.weights) new_tensor.additional_features = z.additional_features return new_tensor
null
6,362
import importlib import torch import os from collections import OrderedDict The provided code snippet includes necessary dependencies for implementing the `get_func` function. Write a Python function `def get_func(func_name)` to solve the following problem: Helper to return a function object by name. func_name must identify a function in this module or the path to a function relative to the base 'modeling' module. Here is the function: def get_func(func_name): """Helper to return a function object by name. func_name must identify a function in this module or the path to a function relative to the base 'modeling' module. """ if func_name == '': return None try: parts = func_name.split('.') # Refers to a function in this module if len(parts) == 1: return globals()[parts[0]] # Otherwise, assume we're referencing a module under modeling module_name = 'lib.' + '.'.join(parts[:-1]) module = importlib.import_module(module_name) return getattr(module, parts[-1]) except Exception: print('Failed to f1ind function: %s', func_name) raise
Helper to return a function object by name. func_name must identify a function in this module or the path to a function relative to the base 'modeling' module.
6,363
import importlib import torch import os from collections import OrderedDict def strip_prefix_if_present(state_dict, prefix): keys = sorted(state_dict.keys()) if not all(key.startswith(prefix) for key in keys): return state_dict stripped_state_dict = OrderedDict() for key, value in state_dict.items(): stripped_state_dict[key.replace(prefix, "")] = value return stripped_state_dict The provided code snippet includes necessary dependencies for implementing the `load_ckpt` function. Write a Python function `def load_ckpt(args, depth_model, shift_model, focal_model)` to solve the following problem: Load checkpoint. Here is the function: def load_ckpt(args, depth_model, shift_model, focal_model): """ Load checkpoint. """ if os.path.isfile(args.load_ckpt): print("loading checkpoint %s" % args.load_ckpt) checkpoint = torch.load(args.load_ckpt) if shift_model is not None: shift_model.load_state_dict(strip_prefix_if_present(checkpoint['shift_model'], 'module.'), strict=True) if focal_model is not None: focal_model.load_state_dict(strip_prefix_if_present(checkpoint['focal_model'], 'module.'), strict=True) depth_model.load_state_dict(strip_prefix_if_present(checkpoint['depth_model'], "module."), strict=True) del checkpoint torch.cuda.empty_cache()
Load checkpoint.
6,364
import torch.nn as nn import torch.nn as NN The provided code snippet includes necessary dependencies for implementing the `conv3x3` function. Write a Python function `def conv3x3(in_planes, out_planes, stride=1)` to solve the following problem: 3x3 convolution with padding Here is the function: def conv3x3(in_planes, out_planes, stride=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
3x3 convolution with padding
6,365
import torch.nn as nn import torch.nn as NN class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride) self.bn1 = NN.BatchNorm2d(planes) #NN.BatchNorm2d self.relu = nn.ReLU(inplace=True) self.conv2 = conv3x3(planes, planes) self.bn2 = NN.BatchNorm2d(planes) #NN.BatchNorm2d self.downsample = downsample self.stride = stride def forward(self, x): residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) if self.downsample is not None: residual = self.downsample(x) out += residual out = self.relu(out) return out class ResNet(nn.Module): def __init__(self, block, layers, num_classes=1000): self.inplanes = 64 super(ResNet, self).__init__() self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = NN.BatchNorm2d(64) #NN.BatchNorm2d self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) self.layer1 = self._make_layer(block, 64, layers[0]) self.layer2 = self._make_layer(block, 128, layers[1], stride=2) self.layer3 = self._make_layer(block, 256, layers[2], stride=2) self.layer4 = self._make_layer(block, 512, layers[3], stride=2) #self.avgpool = nn.AvgPool2d(7, stride=1) #self.fc = nn.Linear(512 * block.expansion, num_classes) for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') elif isinstance(m, nn.BatchNorm2d): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) def _make_layer(self, block, planes, blocks, stride=1): downsample = None if stride != 1 or self.inplanes != planes * block.expansion: downsample = nn.Sequential( nn.Conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=False), NN.BatchNorm2d(planes * block.expansion), #NN.BatchNorm2d ) layers = [] layers.append(block(self.inplanes, planes, stride, downsample)) self.inplanes = planes * block.expansion for i in range(1, blocks): layers.append(block(self.inplanes, planes)) return nn.Sequential(*layers) def forward(self, x): features = [] x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.maxpool(x) x = self.layer1(x) features.append(x) x = self.layer2(x) features.append(x) x = self.layer3(x) features.append(x) x = self.layer4(x) features.append(x) return features The provided code snippet includes necessary dependencies for implementing the `resnet18` function. Write a Python function `def resnet18(pretrained=True, **kwargs)` to solve the following problem: Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet Here is the function: def resnet18(pretrained=True, **kwargs): """Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs) return model
Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
6,366
import torch.nn as nn import torch.nn as NN class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride) self.bn1 = NN.BatchNorm2d(planes) #NN.BatchNorm2d self.relu = nn.ReLU(inplace=True) self.conv2 = conv3x3(planes, planes) self.bn2 = NN.BatchNorm2d(planes) #NN.BatchNorm2d self.downsample = downsample self.stride = stride def forward(self, x): residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) if self.downsample is not None: residual = self.downsample(x) out += residual out = self.relu(out) return out class ResNet(nn.Module): def __init__(self, block, layers, num_classes=1000): self.inplanes = 64 super(ResNet, self).__init__() self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = NN.BatchNorm2d(64) #NN.BatchNorm2d self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) self.layer1 = self._make_layer(block, 64, layers[0]) self.layer2 = self._make_layer(block, 128, layers[1], stride=2) self.layer3 = self._make_layer(block, 256, layers[2], stride=2) self.layer4 = self._make_layer(block, 512, layers[3], stride=2) #self.avgpool = nn.AvgPool2d(7, stride=1) #self.fc = nn.Linear(512 * block.expansion, num_classes) for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') elif isinstance(m, nn.BatchNorm2d): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) def _make_layer(self, block, planes, blocks, stride=1): downsample = None if stride != 1 or self.inplanes != planes * block.expansion: downsample = nn.Sequential( nn.Conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=False), NN.BatchNorm2d(planes * block.expansion), #NN.BatchNorm2d ) layers = [] layers.append(block(self.inplanes, planes, stride, downsample)) self.inplanes = planes * block.expansion for i in range(1, blocks): layers.append(block(self.inplanes, planes)) return nn.Sequential(*layers) def forward(self, x): features = [] x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.maxpool(x) x = self.layer1(x) features.append(x) x = self.layer2(x) features.append(x) x = self.layer3(x) features.append(x) x = self.layer4(x) features.append(x) return features The provided code snippet includes necessary dependencies for implementing the `resnet34` function. Write a Python function `def resnet34(pretrained=True, **kwargs)` to solve the following problem: Constructs a ResNet-34 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet Here is the function: def resnet34(pretrained=True, **kwargs): """Constructs a ResNet-34 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs) return model
Constructs a ResNet-34 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
6,367
import torch.nn as nn import torch.nn as NN class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.bn1 = NN.BatchNorm2d(planes) #NN.BatchNorm2d self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) self.bn2 = NN.BatchNorm2d(planes) #NN.BatchNorm2d self.conv3 = nn.Conv2d(planes, planes * self.expansion, kernel_size=1, bias=False) self.bn3 = NN.BatchNorm2d(planes * self.expansion) #NN.BatchNorm2d self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride def forward(self, x): residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) if self.downsample is not None: residual = self.downsample(x) out += residual out = self.relu(out) return out class ResNet(nn.Module): def __init__(self, block, layers, num_classes=1000): self.inplanes = 64 super(ResNet, self).__init__() self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = NN.BatchNorm2d(64) #NN.BatchNorm2d self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) self.layer1 = self._make_layer(block, 64, layers[0]) self.layer2 = self._make_layer(block, 128, layers[1], stride=2) self.layer3 = self._make_layer(block, 256, layers[2], stride=2) self.layer4 = self._make_layer(block, 512, layers[3], stride=2) #self.avgpool = nn.AvgPool2d(7, stride=1) #self.fc = nn.Linear(512 * block.expansion, num_classes) for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') elif isinstance(m, nn.BatchNorm2d): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) def _make_layer(self, block, planes, blocks, stride=1): downsample = None if stride != 1 or self.inplanes != planes * block.expansion: downsample = nn.Sequential( nn.Conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=False), NN.BatchNorm2d(planes * block.expansion), #NN.BatchNorm2d ) layers = [] layers.append(block(self.inplanes, planes, stride, downsample)) self.inplanes = planes * block.expansion for i in range(1, blocks): layers.append(block(self.inplanes, planes)) return nn.Sequential(*layers) def forward(self, x): features = [] x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.maxpool(x) x = self.layer1(x) features.append(x) x = self.layer2(x) features.append(x) x = self.layer3(x) features.append(x) x = self.layer4(x) features.append(x) return features The provided code snippet includes necessary dependencies for implementing the `resnet50` function. Write a Python function `def resnet50(pretrained=True, **kwargs)` to solve the following problem: Constructs a ResNet-50 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet Here is the function: def resnet50(pretrained=True, **kwargs): """Constructs a ResNet-50 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs) return model
Constructs a ResNet-50 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
6,368
import torch.nn as nn import torch.nn as NN class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.bn1 = NN.BatchNorm2d(planes) #NN.BatchNorm2d self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) self.bn2 = NN.BatchNorm2d(planes) #NN.BatchNorm2d self.conv3 = nn.Conv2d(planes, planes * self.expansion, kernel_size=1, bias=False) self.bn3 = NN.BatchNorm2d(planes * self.expansion) #NN.BatchNorm2d self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride def forward(self, x): residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) if self.downsample is not None: residual = self.downsample(x) out += residual out = self.relu(out) return out class ResNet(nn.Module): def __init__(self, block, layers, num_classes=1000): self.inplanes = 64 super(ResNet, self).__init__() self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = NN.BatchNorm2d(64) #NN.BatchNorm2d self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) self.layer1 = self._make_layer(block, 64, layers[0]) self.layer2 = self._make_layer(block, 128, layers[1], stride=2) self.layer3 = self._make_layer(block, 256, layers[2], stride=2) self.layer4 = self._make_layer(block, 512, layers[3], stride=2) #self.avgpool = nn.AvgPool2d(7, stride=1) #self.fc = nn.Linear(512 * block.expansion, num_classes) for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') elif isinstance(m, nn.BatchNorm2d): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) def _make_layer(self, block, planes, blocks, stride=1): downsample = None if stride != 1 or self.inplanes != planes * block.expansion: downsample = nn.Sequential( nn.Conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=False), NN.BatchNorm2d(planes * block.expansion), #NN.BatchNorm2d ) layers = [] layers.append(block(self.inplanes, planes, stride, downsample)) self.inplanes = planes * block.expansion for i in range(1, blocks): layers.append(block(self.inplanes, planes)) return nn.Sequential(*layers) def forward(self, x): features = [] x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.maxpool(x) x = self.layer1(x) features.append(x) x = self.layer2(x) features.append(x) x = self.layer3(x) features.append(x) x = self.layer4(x) features.append(x) return features The provided code snippet includes necessary dependencies for implementing the `resnet101` function. Write a Python function `def resnet101(pretrained=True, **kwargs)` to solve the following problem: Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet Here is the function: def resnet101(pretrained=True, **kwargs): """Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs) return model
Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
6,369
import torch.nn as nn import torch.nn as NN class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.bn1 = NN.BatchNorm2d(planes) #NN.BatchNorm2d self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) self.bn2 = NN.BatchNorm2d(planes) #NN.BatchNorm2d self.conv3 = nn.Conv2d(planes, planes * self.expansion, kernel_size=1, bias=False) self.bn3 = NN.BatchNorm2d(planes * self.expansion) #NN.BatchNorm2d self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride def forward(self, x): residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) if self.downsample is not None: residual = self.downsample(x) out += residual out = self.relu(out) return out class ResNet(nn.Module): def __init__(self, block, layers, num_classes=1000): self.inplanes = 64 super(ResNet, self).__init__() self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = NN.BatchNorm2d(64) #NN.BatchNorm2d self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) self.layer1 = self._make_layer(block, 64, layers[0]) self.layer2 = self._make_layer(block, 128, layers[1], stride=2) self.layer3 = self._make_layer(block, 256, layers[2], stride=2) self.layer4 = self._make_layer(block, 512, layers[3], stride=2) #self.avgpool = nn.AvgPool2d(7, stride=1) #self.fc = nn.Linear(512 * block.expansion, num_classes) for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') elif isinstance(m, nn.BatchNorm2d): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) def _make_layer(self, block, planes, blocks, stride=1): downsample = None if stride != 1 or self.inplanes != planes * block.expansion: downsample = nn.Sequential( nn.Conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=False), NN.BatchNorm2d(planes * block.expansion), #NN.BatchNorm2d ) layers = [] layers.append(block(self.inplanes, planes, stride, downsample)) self.inplanes = planes * block.expansion for i in range(1, blocks): layers.append(block(self.inplanes, planes)) return nn.Sequential(*layers) def forward(self, x): features = [] x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.maxpool(x) x = self.layer1(x) features.append(x) x = self.layer2(x) features.append(x) x = self.layer3(x) features.append(x) x = self.layer4(x) features.append(x) return features The provided code snippet includes necessary dependencies for implementing the `resnet152` function. Write a Python function `def resnet152(pretrained=True, **kwargs)` to solve the following problem: Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet Here is the function: def resnet152(pretrained=True, **kwargs): """Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs) return model
Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
6,370
import torch import torch.nn as nn import torch.nn.init as init from lib import Resnet, Resnext_torch class DepthNet(nn.Module): __factory = { 18: Resnet.resnet18, 34: Resnet.resnet34, 50: Resnet.resnet50, 101: Resnet.resnet101, 152: Resnet.resnet152 } def __init__(self, backbone='resnet', depth=50, upfactors=[2, 2, 2, 2]): super(DepthNet, self).__init__() self.backbone = backbone self.depth = depth self.pretrained = False self.inchannels = [256, 512, 1024, 2048] self.midchannels = [256, 256, 256, 512] self.upfactors = upfactors self.outchannels = 1 # Build model if self.backbone == 'resnet': if self.depth not in DepthNet.__factory: raise KeyError("Unsupported depth:", self.depth) self.encoder = DepthNet.__factory[depth](pretrained=self.pretrained) elif self.backbone == 'resnext101_32x8d': self.encoder = Resnext_torch.resnext101_32x8d(pretrained=self.pretrained) else: self.encoder = Resnext_torch.resnext101(pretrained=self.pretrained) def forward(self, x): x = self.encoder(x) # 1/32, 1/16, 1/8, 1/4 return x def resnet50_stride32(): return DepthNet(backbone='resnet', depth=50, upfactors=[2, 2, 2, 2])
null
6,371
import torch import torch.nn as nn import torch.nn.init as init from lib import Resnet, Resnext_torch class DepthNet(nn.Module): def __init__(self, backbone='resnet', depth=50, upfactors=[2, 2, 2, 2]): def forward(self, x): def resnext101_stride32x8d(): return DepthNet(backbone='resnext101_32x8d', depth=101, upfactors=[2, 2, 2, 2])
null
6,372
import torch.nn as nn The provided code snippet includes necessary dependencies for implementing the `conv3x3` function. Write a Python function `def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1)` to solve the following problem: 3x3 convolution with padding Here is the function: def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, bias=False, dilation=dilation)
3x3 convolution with padding
6,373
import torch.nn as nn The provided code snippet includes necessary dependencies for implementing the `conv1x1` function. Write a Python function `def conv1x1(in_planes, out_planes, stride=1)` to solve the following problem: 1x1 convolution Here is the function: def conv1x1(in_planes, out_planes, stride=1): """1x1 convolution""" return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
1x1 convolution
6,374
import torch.nn as nn class Bottleneck(nn.Module): # Bottleneck in torchvision places the stride for downsampling at 3x3 convolution(self.conv2) # while original implementation places the stride at the first 1x1 convolution(self.conv1) # according to "Deep residual learning for image recognition"https://arxiv.org/abs/1512.03385. # This variant is also known as ResNet V1.5 and improves accuracy according to # https://ngc.nvidia.com/catalog/model-scripts/nvidia:resnet_50_v1_5_for_pytorch. expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, base_width=64, dilation=1, norm_layer=None): super(Bottleneck, self).__init__() if norm_layer is None: norm_layer = nn.BatchNorm2d width = int(planes * (base_width / 64.)) * groups # Both self.conv2 and self.downsample layers downsample the input when stride != 1 self.conv1 = conv1x1(inplanes, width) self.bn1 = norm_layer(width) self.conv2 = conv3x3(width, width, stride, groups, dilation) self.bn2 = norm_layer(width) self.conv3 = conv1x1(width, planes * self.expansion) self.bn3 = norm_layer(planes * self.expansion) self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride def forward(self, x): identity = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) if self.downsample is not None: identity = self.downsample(x) out += identity out = self.relu(out) return out class ResNet(nn.Module): def __init__(self, block, layers, num_classes=1000, zero_init_residual=False, groups=1, width_per_group=64, replace_stride_with_dilation=None, norm_layer=None): super(ResNet, self).__init__() if norm_layer is None: norm_layer = nn.BatchNorm2d self._norm_layer = norm_layer self.inplanes = 64 self.dilation = 1 if replace_stride_with_dilation is None: # each element in the tuple indicates if we should replace # the 2x2 stride with a dilated convolution instead replace_stride_with_dilation = [False, False, False] if len(replace_stride_with_dilation) != 3: raise ValueError("replace_stride_with_dilation should be None " "or a 3-element tuple, got {}".format(replace_stride_with_dilation)) self.groups = groups self.base_width = width_per_group self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = norm_layer(self.inplanes) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) self.layer1 = self._make_layer(block, 64, layers[0]) self.layer2 = self._make_layer(block, 128, layers[1], stride=2, dilate=replace_stride_with_dilation[0]) self.layer3 = self._make_layer(block, 256, layers[2], stride=2, dilate=replace_stride_with_dilation[1]) self.layer4 = self._make_layer(block, 512, layers[3], stride=2, dilate=replace_stride_with_dilation[2]) #self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) #self.fc = nn.Linear(512 * block.expansion, num_classes) for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) # Zero-initialize the last BN in each residual branch, # so that the residual branch starts with zeros, and each residual block behaves like an identity. # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677 if zero_init_residual: for m in self.modules(): if isinstance(m, Bottleneck): nn.init.constant_(m.bn3.weight, 0) elif isinstance(m, BasicBlock): nn.init.constant_(m.bn2.weight, 0) def _make_layer(self, block, planes, blocks, stride=1, dilate=False): norm_layer = self._norm_layer downsample = None previous_dilation = self.dilation if dilate: self.dilation *= stride stride = 1 if stride != 1 or self.inplanes != planes * block.expansion: downsample = nn.Sequential( conv1x1(self.inplanes, planes * block.expansion, stride), norm_layer(planes * block.expansion), ) layers = [] layers.append(block(self.inplanes, planes, stride, downsample, self.groups, self.base_width, previous_dilation, norm_layer)) self.inplanes = planes * block.expansion for _ in range(1, blocks): layers.append(block(self.inplanes, planes, groups=self.groups, base_width=self.base_width, dilation=self.dilation, norm_layer=norm_layer)) return nn.Sequential(*layers) def _forward_impl(self, x): # See note [TorchScript super()] features = [] x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.maxpool(x) x = self.layer1(x) features.append(x) x = self.layer2(x) features.append(x) x = self.layer3(x) features.append(x) x = self.layer4(x) features.append(x) #x = self.avgpool(x) #x = torch.flatten(x, 1) #x = self.fc(x) return features def forward(self, x): return self._forward_impl(x) The provided code snippet includes necessary dependencies for implementing the `resnext101_32x8d` function. Write a Python function `def resnext101_32x8d(pretrained=True, **kwargs)` to solve the following problem: Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet Here is the function: def resnext101_32x8d(pretrained=True, **kwargs): """Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ kwargs['groups'] = 32 kwargs['width_per_group'] = 8 model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs) return model
Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
6,375
import numpy as np import cv2 import math The provided code snippet includes necessary dependencies for implementing the `apply_min_size` function. Write a Python function `def apply_min_size(sample, size, image_interpolation_method=cv2.INTER_AREA)` to solve the following problem: Rezise the sample to ensure the given size. Keeps aspect ratio. Args: sample (dict): sample size (tuple): image size Returns: tuple: new size Here is the function: def apply_min_size(sample, size, image_interpolation_method=cv2.INTER_AREA): """Rezise the sample to ensure the given size. Keeps aspect ratio. Args: sample (dict): sample size (tuple): image size Returns: tuple: new size """ shape = list(sample["disparity"].shape) if shape[0] >= size[0] and shape[1] >= size[1]: return sample scale = [0, 0] scale[0] = size[0] / shape[0] scale[1] = size[1] / shape[1] scale = max(scale) shape[0] = math.ceil(scale * shape[0]) shape[1] = math.ceil(scale * shape[1]) # resize sample["image"] = cv2.resize( sample["image"], tuple(shape[::-1]), interpolation=image_interpolation_method ) sample["disparity"] = cv2.resize( sample["disparity"], tuple(shape[::-1]), interpolation=cv2.INTER_NEAREST ) sample["mask"] = cv2.resize( sample["mask"].astype(np.float32), tuple(shape[::-1]), interpolation=cv2.INTER_NEAREST, ) sample["mask"] = sample["mask"].astype(bool) return tuple(shape)
Rezise the sample to ensure the given size. Keeps aspect ratio. Args: sample (dict): sample size (tuple): image size Returns: tuple: new size
6,376
import timm import torch import types import numpy as np import torch.nn.functional as F from .utils import forward_adapted_unflatten, make_backbone_default from timm.models.beit import gen_relative_position_index from torch.utils.checkpoint import checkpoint from typing import Optional def forward_adapted_unflatten(pretrained, x, function_name="forward_features"): b, c, h, w = x.shape exec(f"glob = pretrained.model.{function_name}(x)") layer_1 = pretrained.activations["1"] layer_2 = pretrained.activations["2"] layer_3 = pretrained.activations["3"] layer_4 = pretrained.activations["4"] layer_1 = pretrained.act_postprocess1[0:2](layer_1) layer_2 = pretrained.act_postprocess2[0:2](layer_2) layer_3 = pretrained.act_postprocess3[0:2](layer_3) layer_4 = pretrained.act_postprocess4[0:2](layer_4) unflatten = nn.Sequential( nn.Unflatten( 2, torch.Size( [ h // pretrained.model.patch_size[1], w // pretrained.model.patch_size[0], ] ), ) ) if layer_1.ndim == 3: layer_1 = unflatten(layer_1) if layer_2.ndim == 3: layer_2 = unflatten(layer_2) if layer_3.ndim == 3: layer_3 = unflatten(layer_3) if layer_4.ndim == 3: layer_4 = unflatten(layer_4) layer_1 = pretrained.act_postprocess1[3: len(pretrained.act_postprocess1)](layer_1) layer_2 = pretrained.act_postprocess2[3: len(pretrained.act_postprocess2)](layer_2) layer_3 = pretrained.act_postprocess3[3: len(pretrained.act_postprocess3)](layer_3) layer_4 = pretrained.act_postprocess4[3: len(pretrained.act_postprocess4)](layer_4) return layer_1, layer_2, layer_3, layer_4 def forward_beit(pretrained, x): return forward_adapted_unflatten(pretrained, x, "forward_features")
null
6,377
import timm import torch import torch.nn as nn import numpy as np from .utils import activations, get_activation, Transpose activations = {} def forward_levit(pretrained, x): pretrained.model.forward_features(x) layer_1 = pretrained.activations["1"] layer_2 = pretrained.activations["2"] layer_3 = pretrained.activations["3"] layer_1 = pretrained.act_postprocess1(layer_1) layer_2 = pretrained.act_postprocess2(layer_2) layer_3 = pretrained.act_postprocess3(layer_3) return layer_1, layer_2, layer_3
null
6,378
import timm import torch import torch.nn as nn import numpy as np from .utils import activations, get_activation, Transpose class ConvTransposeNorm(nn.Sequential): """ Modification of https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/levit.py: ConvNorm such that ConvTranspose2d is used instead of Conv2d. """ def __init__( self, in_chs, out_chs, kernel_size=1, stride=1, pad=0, dilation=1, groups=1, bn_weight_init=1): super().__init__() self.add_module('c', nn.ConvTranspose2d(in_chs, out_chs, kernel_size, stride, pad, dilation, groups, bias=False)) self.add_module('bn', nn.BatchNorm2d(out_chs)) nn.init.constant_(self.bn.weight, bn_weight_init) def fuse(self): c, bn = self._modules.values() w = bn.weight / (bn.running_var + bn.eps) ** 0.5 w = c.weight * w[:, None, None, None] b = bn.bias - bn.running_mean * bn.weight / (bn.running_var + bn.eps) ** 0.5 m = nn.ConvTranspose2d( w.size(1), w.size(0), w.shape[2:], stride=self.c.stride, padding=self.c.padding, dilation=self.c.dilation, groups=self.c.groups) m.weight.data.copy_(w) m.bias.data.copy_(b) return m The provided code snippet includes necessary dependencies for implementing the `stem_b4_transpose` function. Write a Python function `def stem_b4_transpose(in_chs, out_chs, activation)` to solve the following problem: Modification of https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/levit.py: stem_b16 such that ConvTranspose2d is used instead of Conv2d and stem is also reduced to the half. Here is the function: def stem_b4_transpose(in_chs, out_chs, activation): """ Modification of https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/levit.py: stem_b16 such that ConvTranspose2d is used instead of Conv2d and stem is also reduced to the half. """ return nn.Sequential( ConvTransposeNorm(in_chs, out_chs, 3, 2, 1), activation(), ConvTransposeNorm(out_chs, out_chs // 2, 3, 2, 1), activation())
Modification of https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/levit.py: stem_b16 such that ConvTranspose2d is used instead of Conv2d and stem is also reduced to the half.
6,379
import timm import torch.nn as nn from pathlib import Path from .utils import activations, forward_default, get_activation from functools import partial import torch import torch.utils.checkpoint as checkpoint from einops import rearrange from timm.models.layers import DropPath, trunc_normal_ from timm.models.registry import register_model from torch import nn The provided code snippet includes necessary dependencies for implementing the `merge_pre_bn` function. Write a Python function `def merge_pre_bn(module, pre_bn_1, pre_bn_2=None)` to solve the following problem: Merge pre BN to reduce inference runtime. Here is the function: def merge_pre_bn(module, pre_bn_1, pre_bn_2=None): """ Merge pre BN to reduce inference runtime. """ weight = module.weight.data if module.bias is None: zeros = torch.zeros(module.out_channels, device=weight.device).type(weight.type()) module.bias = nn.Parameter(zeros) bias = module.bias.data if pre_bn_2 is None: assert pre_bn_1.track_running_stats is True, "Unsupport bn_module.track_running_stats is False" assert pre_bn_1.affine is True, "Unsupport bn_module.affine is False" scale_invstd = pre_bn_1.running_var.add(pre_bn_1.eps).pow(-0.5) extra_weight = scale_invstd * pre_bn_1.weight extra_bias = pre_bn_1.bias - pre_bn_1.weight * pre_bn_1.running_mean * scale_invstd else: assert pre_bn_1.track_running_stats is True, "Unsupport bn_module.track_running_stats is False" assert pre_bn_1.affine is True, "Unsupport bn_module.affine is False" assert pre_bn_2.track_running_stats is True, "Unsupport bn_module.track_running_stats is False" assert pre_bn_2.affine is True, "Unsupport bn_module.affine is False" scale_invstd_1 = pre_bn_1.running_var.add(pre_bn_1.eps).pow(-0.5) scale_invstd_2 = pre_bn_2.running_var.add(pre_bn_2.eps).pow(-0.5) extra_weight = scale_invstd_1 * pre_bn_1.weight * scale_invstd_2 * pre_bn_2.weight extra_bias = scale_invstd_2 * pre_bn_2.weight *(pre_bn_1.bias - pre_bn_1.weight * pre_bn_1.running_mean * scale_invstd_1 - pre_bn_2.running_mean) + pre_bn_2.bias if isinstance(module, nn.Linear): extra_bias = weight @ extra_bias weight.mul_(extra_weight.view(1, weight.size(1)).expand_as(weight)) elif isinstance(module, nn.Conv2d): assert weight.shape[2] == 1 and weight.shape[3] == 1 weight = weight.reshape(weight.shape[0], weight.shape[1]) extra_bias = weight @ extra_bias weight.mul_(extra_weight.view(1, weight.size(1)).expand_as(weight)) weight = weight.reshape(weight.shape[0], weight.shape[1], 1, 1) bias.add_(extra_bias) module.weight.data = weight module.bias.data = bias
Merge pre BN to reduce inference runtime.
6,380
import timm import torch.nn as nn from pathlib import Path from .utils import activations, forward_default, get_activation from functools import partial import torch import torch.utils.checkpoint as checkpoint from einops import rearrange from timm.models.layers import DropPath, trunc_normal_ from timm.models.registry import register_model from torch import nn def _make_divisible(v, divisor, min_value=None): if min_value is None: min_value = divisor new_v = max(min_value, int(v + divisor / 2) // divisor * divisor) # Make sure that round down does not go down by more than 10%. if new_v < 0.9 * v: new_v += divisor return new_v
null
6,381
import timm import torch.nn as nn from pathlib import Path from .utils import activations, forward_default, get_activation from functools import partial import torch import torch.utils.checkpoint as checkpoint from einops import rearrange from timm.models.layers import DropPath, trunc_normal_ from timm.models.registry import register_model from torch import nn class NextViT(nn.Module): def __init__(self, stem_chs, depths, path_dropout, attn_drop=0, drop=0, num_classes=1000, strides=[1, 2, 2, 2], sr_ratios=[8, 4, 2, 1], head_dim=32, mix_block_ratio=0.75, use_checkpoint=False): def merge_bn(self): def _initialize_weights(self): def forward(self, x): def nextvit_small(pretrained=False, pretrained_cfg=None, **kwargs): model = NextViT(stem_chs=[64, 32, 64], depths=[3, 4, 10, 3], path_dropout=0.1, **kwargs) return model
null
6,382
import timm import torch.nn as nn from pathlib import Path from .utils import activations, forward_default, get_activation from functools import partial import torch import torch.utils.checkpoint as checkpoint from einops import rearrange from timm.models.layers import DropPath, trunc_normal_ from timm.models.registry import register_model from torch import nn class NextViT(nn.Module): def __init__(self, stem_chs, depths, path_dropout, attn_drop=0, drop=0, num_classes=1000, strides=[1, 2, 2, 2], sr_ratios=[8, 4, 2, 1], head_dim=32, mix_block_ratio=0.75, use_checkpoint=False): super(NextViT, self).__init__() self.use_checkpoint = use_checkpoint self.stage_out_channels = [[96] * (depths[0]), [192] * (depths[1] - 1) + [256], [384, 384, 384, 384, 512] * (depths[2] // 5), [768] * (depths[3] - 1) + [1024]] # Next Hybrid Strategy self.stage_block_types = [[NCB] * depths[0], [NCB] * (depths[1] - 1) + [NTB], [NCB, NCB, NCB, NCB, NTB] * (depths[2] // 5), [NCB] * (depths[3] - 1) + [NTB]] self.stem = nn.Sequential( ConvBNReLU(3, stem_chs[0], kernel_size=3, stride=2), ConvBNReLU(stem_chs[0], stem_chs[1], kernel_size=3, stride=1), ConvBNReLU(stem_chs[1], stem_chs[2], kernel_size=3, stride=1), ConvBNReLU(stem_chs[2], stem_chs[2], kernel_size=3, stride=2), ) input_channel = stem_chs[-1] features = [] idx = 0 dpr = [x.item() for x in torch.linspace(0, path_dropout, sum(depths))] # stochastic depth decay rule for stage_id in range(len(depths)): numrepeat = depths[stage_id] output_channels = self.stage_out_channels[stage_id] block_types = self.stage_block_types[stage_id] for block_id in range(numrepeat): if strides[stage_id] == 2 and block_id == 0: stride = 2 else: stride = 1 output_channel = output_channels[block_id] block_type = block_types[block_id] if block_type is NCB: layer = NCB(input_channel, output_channel, stride=stride, path_dropout=dpr[idx + block_id], drop=drop, head_dim=head_dim) features.append(layer) elif block_type is NTB: layer = NTB(input_channel, output_channel, path_dropout=dpr[idx + block_id], stride=stride, sr_ratio=sr_ratios[stage_id], head_dim=head_dim, mix_block_ratio=mix_block_ratio, attn_drop=attn_drop, drop=drop) features.append(layer) input_channel = output_channel idx += numrepeat self.features = nn.Sequential(*features) self.norm = nn.BatchNorm2d(output_channel, eps=NORM_EPS) self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) self.proj_head = nn.Sequential( nn.Linear(output_channel, num_classes), ) self.stage_out_idx = [sum(depths[:idx + 1]) - 1 for idx in range(len(depths))] print('initialize_weights...') self._initialize_weights() def merge_bn(self): self.eval() for idx, module in self.named_modules(): if isinstance(module, NCB) or isinstance(module, NTB): module.merge_bn() def _initialize_weights(self): for n, m in self.named_modules(): if isinstance(m, (nn.BatchNorm2d, nn.GroupNorm, nn.LayerNorm, nn.BatchNorm1d)): nn.init.constant_(m.weight, 1.0) nn.init.constant_(m.bias, 0) elif isinstance(m, nn.Linear): trunc_normal_(m.weight, std=.02) if hasattr(m, 'bias') and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.Conv2d): trunc_normal_(m.weight, std=.02) if hasattr(m, 'bias') and m.bias is not None: nn.init.constant_(m.bias, 0) def forward(self, x): x = self.stem(x) for idx, layer in enumerate(self.features): if self.use_checkpoint: x = checkpoint.checkpoint(layer, x) else: x = layer(x) x = self.norm(x) x = self.avgpool(x) x = torch.flatten(x, 1) x = self.proj_head(x) return x def nextvit_base(pretrained=False, pretrained_cfg=None, **kwargs): model = NextViT(stem_chs=[64, 32, 64], depths=[3, 4, 20, 3], path_dropout=0.2, **kwargs) return model
null
6,383
import timm import torch.nn as nn from pathlib import Path from .utils import activations, forward_default, get_activation from functools import partial import torch import torch.utils.checkpoint as checkpoint from einops import rearrange from timm.models.layers import DropPath, trunc_normal_ from timm.models.registry import register_model from torch import nn class NextViT(nn.Module): def __init__(self, stem_chs, depths, path_dropout, attn_drop=0, drop=0, num_classes=1000, strides=[1, 2, 2, 2], sr_ratios=[8, 4, 2, 1], head_dim=32, mix_block_ratio=0.75, use_checkpoint=False): super(NextViT, self).__init__() self.use_checkpoint = use_checkpoint self.stage_out_channels = [[96] * (depths[0]), [192] * (depths[1] - 1) + [256], [384, 384, 384, 384, 512] * (depths[2] // 5), [768] * (depths[3] - 1) + [1024]] # Next Hybrid Strategy self.stage_block_types = [[NCB] * depths[0], [NCB] * (depths[1] - 1) + [NTB], [NCB, NCB, NCB, NCB, NTB] * (depths[2] // 5), [NCB] * (depths[3] - 1) + [NTB]] self.stem = nn.Sequential( ConvBNReLU(3, stem_chs[0], kernel_size=3, stride=2), ConvBNReLU(stem_chs[0], stem_chs[1], kernel_size=3, stride=1), ConvBNReLU(stem_chs[1], stem_chs[2], kernel_size=3, stride=1), ConvBNReLU(stem_chs[2], stem_chs[2], kernel_size=3, stride=2), ) input_channel = stem_chs[-1] features = [] idx = 0 dpr = [x.item() for x in torch.linspace(0, path_dropout, sum(depths))] # stochastic depth decay rule for stage_id in range(len(depths)): numrepeat = depths[stage_id] output_channels = self.stage_out_channels[stage_id] block_types = self.stage_block_types[stage_id] for block_id in range(numrepeat): if strides[stage_id] == 2 and block_id == 0: stride = 2 else: stride = 1 output_channel = output_channels[block_id] block_type = block_types[block_id] if block_type is NCB: layer = NCB(input_channel, output_channel, stride=stride, path_dropout=dpr[idx + block_id], drop=drop, head_dim=head_dim) features.append(layer) elif block_type is NTB: layer = NTB(input_channel, output_channel, path_dropout=dpr[idx + block_id], stride=stride, sr_ratio=sr_ratios[stage_id], head_dim=head_dim, mix_block_ratio=mix_block_ratio, attn_drop=attn_drop, drop=drop) features.append(layer) input_channel = output_channel idx += numrepeat self.features = nn.Sequential(*features) self.norm = nn.BatchNorm2d(output_channel, eps=NORM_EPS) self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) self.proj_head = nn.Sequential( nn.Linear(output_channel, num_classes), ) self.stage_out_idx = [sum(depths[:idx + 1]) - 1 for idx in range(len(depths))] print('initialize_weights...') self._initialize_weights() def merge_bn(self): self.eval() for idx, module in self.named_modules(): if isinstance(module, NCB) or isinstance(module, NTB): module.merge_bn() def _initialize_weights(self): for n, m in self.named_modules(): if isinstance(m, (nn.BatchNorm2d, nn.GroupNorm, nn.LayerNorm, nn.BatchNorm1d)): nn.init.constant_(m.weight, 1.0) nn.init.constant_(m.bias, 0) elif isinstance(m, nn.Linear): trunc_normal_(m.weight, std=.02) if hasattr(m, 'bias') and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.Conv2d): trunc_normal_(m.weight, std=.02) if hasattr(m, 'bias') and m.bias is not None: nn.init.constant_(m.bias, 0) def forward(self, x): x = self.stem(x) for idx, layer in enumerate(self.features): if self.use_checkpoint: x = checkpoint.checkpoint(layer, x) else: x = layer(x) x = self.norm(x) x = self.avgpool(x) x = torch.flatten(x, 1) x = self.proj_head(x) return x def nextvit_large(pretrained=False, pretrained_cfg=None, **kwargs): model = NextViT(stem_chs=[64, 32, 64], depths=[3, 4, 30, 3], path_dropout=0.2, **kwargs) return model
null
6,384
import timm import torch.nn as nn from pathlib import Path from .utils import activations, forward_default, get_activation from functools import partial import torch import torch.utils.checkpoint as checkpoint from einops import rearrange from timm.models.layers import DropPath, trunc_normal_ from timm.models.registry import register_model from torch import nn def forward_default(pretrained, x, function_name="forward_features"): exec(f"pretrained.model.{function_name}(x)") layer_1 = pretrained.activations["1"] layer_2 = pretrained.activations["2"] layer_3 = pretrained.activations["3"] layer_4 = pretrained.activations["4"] if hasattr(pretrained, "act_postprocess1"): layer_1 = pretrained.act_postprocess1(layer_1) if hasattr(pretrained, "act_postprocess2"): layer_2 = pretrained.act_postprocess2(layer_2) if hasattr(pretrained, "act_postprocess3"): layer_3 = pretrained.act_postprocess3(layer_3) if hasattr(pretrained, "act_postprocess4"): layer_4 = pretrained.act_postprocess4(layer_4) return layer_1, layer_2, layer_3, layer_4 def forward_next_vit(pretrained, x): return forward_default(pretrained, x, "forward")
null
6,385
import torch import torch.nn as nn import timm import types import math import torch.nn.functional as F from .utils import (activations, forward_adapted_unflatten, get_activation, get_readout_oper, make_backbone_default, Transpose) def forward_adapted_unflatten(pretrained, x, function_name="forward_features"): b, c, h, w = x.shape exec(f"glob = pretrained.model.{function_name}(x)") layer_1 = pretrained.activations["1"] layer_2 = pretrained.activations["2"] layer_3 = pretrained.activations["3"] layer_4 = pretrained.activations["4"] layer_1 = pretrained.act_postprocess1[0:2](layer_1) layer_2 = pretrained.act_postprocess2[0:2](layer_2) layer_3 = pretrained.act_postprocess3[0:2](layer_3) layer_4 = pretrained.act_postprocess4[0:2](layer_4) unflatten = nn.Sequential( nn.Unflatten( 2, torch.Size( [ h // pretrained.model.patch_size[1], w // pretrained.model.patch_size[0], ] ), ) ) if layer_1.ndim == 3: layer_1 = unflatten(layer_1) if layer_2.ndim == 3: layer_2 = unflatten(layer_2) if layer_3.ndim == 3: layer_3 = unflatten(layer_3) if layer_4.ndim == 3: layer_4 = unflatten(layer_4) layer_1 = pretrained.act_postprocess1[3: len(pretrained.act_postprocess1)](layer_1) layer_2 = pretrained.act_postprocess2[3: len(pretrained.act_postprocess2)](layer_2) layer_3 = pretrained.act_postprocess3[3: len(pretrained.act_postprocess3)](layer_3) layer_4 = pretrained.act_postprocess4[3: len(pretrained.act_postprocess4)](layer_4) return layer_1, layer_2, layer_3, layer_4 def forward_vit(pretrained, x): return forward_adapted_unflatten(pretrained, x, "forward_flex")
null
6,386
import torch import torch.nn as nn import numpy as np from .utils import activations, forward_default, get_activation, Transpose def forward_default(pretrained, x, function_name="forward_features"): exec(f"pretrained.model.{function_name}(x)") layer_1 = pretrained.activations["1"] layer_2 = pretrained.activations["2"] layer_3 = pretrained.activations["3"] layer_4 = pretrained.activations["4"] if hasattr(pretrained, "act_postprocess1"): layer_1 = pretrained.act_postprocess1(layer_1) if hasattr(pretrained, "act_postprocess2"): layer_2 = pretrained.act_postprocess2(layer_2) if hasattr(pretrained, "act_postprocess3"): layer_3 = pretrained.act_postprocess3(layer_3) if hasattr(pretrained, "act_postprocess4"): layer_4 = pretrained.act_postprocess4(layer_4) return layer_1, layer_2, layer_3, layer_4 def forward_swin(pretrained, x): return forward_default(pretrained, x)
null
6,387
import torch import torch.nn as nn from .base_model import BaseModel from .blocks import ( FeatureFusionBlock_custom, Interpolate, _make_encoder, forward_beit, forward_swin, forward_next_vit, forward_levit, forward_vit, ) from .backbones.levit import stem_b4_transpose from timm.models.layers import get_act_layer class FeatureFusionBlock_custom(nn.Module): def __init__(self, features, activation, deconv=False, bn=False, expand=False, align_corners=True, size=None): def forward(self, *xs, size=None): def _make_fusion_block(features, use_bn, size = None): return FeatureFusionBlock_custom( features, nn.ReLU(False), deconv=False, bn=use_bn, expand=False, align_corners=True, size=size, )
null
6,388
import torch import torch.nn as nn from .backbones.beit import ( _make_pretrained_beitl16_512, _make_pretrained_beitl16_384, _make_pretrained_beitb16_384, forward_beit, ) from .backbones.swin_common import ( forward_swin, ) from .backbones.swin2 import ( _make_pretrained_swin2l24_384, _make_pretrained_swin2b24_384, _make_pretrained_swin2t16_256, ) from .backbones.swin import ( _make_pretrained_swinl12_384, ) from .backbones.next_vit import ( _make_pretrained_next_vit_large_6m, forward_next_vit, ) from .backbones.levit import ( _make_pretrained_levit_384, forward_levit, ) from .backbones.vit import ( _make_pretrained_vitb_rn50_384, _make_pretrained_vitl16_384, _make_pretrained_vitb16_384, forward_vit, ) def _make_scratch(in_shape, out_shape, groups=1, expand=False): scratch = nn.Module() out_shape1 = out_shape out_shape2 = out_shape out_shape3 = out_shape if len(in_shape) >= 4: out_shape4 = out_shape if expand: out_shape1 = out_shape out_shape2 = out_shape*2 out_shape3 = out_shape*4 if len(in_shape) >= 4: out_shape4 = out_shape*8 scratch.layer1_rn = nn.Conv2d( in_shape[0], out_shape1, kernel_size=3, stride=1, padding=1, bias=False, groups=groups ) scratch.layer2_rn = nn.Conv2d( in_shape[1], out_shape2, kernel_size=3, stride=1, padding=1, bias=False, groups=groups ) scratch.layer3_rn = nn.Conv2d( in_shape[2], out_shape3, kernel_size=3, stride=1, padding=1, bias=False, groups=groups ) if len(in_shape) >= 4: scratch.layer4_rn = nn.Conv2d( in_shape[3], out_shape4, kernel_size=3, stride=1, padding=1, bias=False, groups=groups ) return scratch def _make_pretrained_efficientnet_lite3(use_pretrained, exportable=False): efficientnet = torch.hub.load( "rwightman/gen-efficientnet-pytorch", "tf_efficientnet_lite3", pretrained=use_pretrained, exportable=exportable ) return _make_efficientnet_backbone(efficientnet) def _make_pretrained_resnext101_wsl(use_pretrained): resnet = torch.hub.load("facebookresearch/WSL-Images", "resnext101_32x8d_wsl") return _make_resnet_backbone(resnet) def _make_pretrained_beitl16_512(pretrained, use_readout="ignore", hooks=None): model = timm.create_model("beit_large_patch16_512", pretrained=pretrained) hooks = [5, 11, 17, 23] if hooks is None else hooks features = [256, 512, 1024, 1024] return _make_beit_backbone( model, features=features, size=[512, 512], hooks=hooks, vit_features=1024, use_readout=use_readout, ) def _make_pretrained_beitl16_384(pretrained, use_readout="ignore", hooks=None): model = timm.create_model("beit_large_patch16_384", pretrained=pretrained) hooks = [5, 11, 17, 23] if hooks is None else hooks return _make_beit_backbone( model, features=[256, 512, 1024, 1024], hooks=hooks, vit_features=1024, use_readout=use_readout, ) def _make_pretrained_beitb16_384(pretrained, use_readout="ignore", hooks=None): model = timm.create_model("beit_base_patch16_384", pretrained=pretrained) hooks = [2, 5, 8, 11] if hooks is None else hooks return _make_beit_backbone( model, features=[96, 192, 384, 768], hooks=hooks, use_readout=use_readout, ) def _make_pretrained_swin2l24_384(pretrained, hooks=None): model = timm.create_model("swinv2_large_window12to24_192to384_22kft1k", pretrained=pretrained) hooks = [1, 1, 17, 1] if hooks == None else hooks return _make_swin_backbone( model, hooks=hooks ) def _make_pretrained_swin2b24_384(pretrained, hooks=None): model = timm.create_model("swinv2_base_window12to24_192to384_22kft1k", pretrained=pretrained) hooks = [1, 1, 17, 1] if hooks == None else hooks return _make_swin_backbone( model, hooks=hooks ) def _make_pretrained_swin2t16_256(pretrained, hooks=None): model = timm.create_model("swinv2_tiny_window16_256", pretrained=pretrained) hooks = [1, 1, 5, 1] if hooks == None else hooks return _make_swin_backbone( model, hooks=hooks, patch_grid=[64, 64] ) def _make_pretrained_swinl12_384(pretrained, hooks=None): model = timm.create_model("swin_large_patch4_window12_384", pretrained=pretrained) hooks = [1, 1, 17, 1] if hooks == None else hooks return _make_swin_backbone( model, hooks=hooks ) def _make_pretrained_next_vit_large_6m(hooks=None): model = timm.create_model("nextvit_large") hooks = [2, 6, 36, 39] if hooks == None else hooks return _make_next_vit_backbone( model, hooks=hooks, ) def _make_pretrained_levit_384(pretrained, hooks=None): model = timm.create_model("levit_384", pretrained=pretrained) hooks = [3, 11, 21] if hooks == None else hooks return _make_levit_backbone( model, hooks=hooks ) def _make_pretrained_vitl16_384(pretrained, use_readout="ignore", hooks=None): model = timm.create_model("vit_large_patch16_384", pretrained=pretrained) hooks = [5, 11, 17, 23] if hooks == None else hooks return _make_vit_b16_backbone( model, features=[256, 512, 1024, 1024], hooks=hooks, vit_features=1024, use_readout=use_readout, ) def _make_pretrained_vitb16_384(pretrained, use_readout="ignore", hooks=None): model = timm.create_model("vit_base_patch16_384", pretrained=pretrained) hooks = [2, 5, 8, 11] if hooks == None else hooks return _make_vit_b16_backbone( model, features=[96, 192, 384, 768], hooks=hooks, use_readout=use_readout ) def _make_pretrained_vitb_rn50_384( pretrained, use_readout="ignore", hooks=None, use_vit_only=False ): model = timm.create_model("vit_base_resnet50_384", pretrained=pretrained) hooks = [0, 1, 8, 11] if hooks == None else hooks return _make_vit_b_rn50_backbone( model, features=[256, 512, 768, 768], size=[384, 384], hooks=hooks, use_vit_only=use_vit_only, use_readout=use_readout, ) def _make_encoder(backbone, features, use_pretrained, groups=1, expand=False, exportable=True, hooks=None, use_vit_only=False, use_readout="ignore", in_features=[96, 256, 512, 1024]): if backbone == "beitl16_512": pretrained = _make_pretrained_beitl16_512( use_pretrained, hooks=hooks, use_readout=use_readout ) scratch = _make_scratch( [256, 512, 1024, 1024], features, groups=groups, expand=expand ) # BEiT_512-L (backbone) elif backbone == "beitl16_384": pretrained = _make_pretrained_beitl16_384( use_pretrained, hooks=hooks, use_readout=use_readout ) scratch = _make_scratch( [256, 512, 1024, 1024], features, groups=groups, expand=expand ) # BEiT_384-L (backbone) elif backbone == "beitb16_384": pretrained = _make_pretrained_beitb16_384( use_pretrained, hooks=hooks, use_readout=use_readout ) scratch = _make_scratch( [96, 192, 384, 768], features, groups=groups, expand=expand ) # BEiT_384-B (backbone) elif backbone == "swin2l24_384": pretrained = _make_pretrained_swin2l24_384( use_pretrained, hooks=hooks ) scratch = _make_scratch( [192, 384, 768, 1536], features, groups=groups, expand=expand ) # Swin2-L/12to24 (backbone) elif backbone == "swin2b24_384": pretrained = _make_pretrained_swin2b24_384( use_pretrained, hooks=hooks ) scratch = _make_scratch( [128, 256, 512, 1024], features, groups=groups, expand=expand ) # Swin2-B/12to24 (backbone) elif backbone == "swin2t16_256": pretrained = _make_pretrained_swin2t16_256( use_pretrained, hooks=hooks ) scratch = _make_scratch( [96, 192, 384, 768], features, groups=groups, expand=expand ) # Swin2-T/16 (backbone) elif backbone == "swinl12_384": pretrained = _make_pretrained_swinl12_384( use_pretrained, hooks=hooks ) scratch = _make_scratch( [192, 384, 768, 1536], features, groups=groups, expand=expand ) # Swin-L/12 (backbone) elif backbone == "next_vit_large_6m": pretrained = _make_pretrained_next_vit_large_6m(hooks=hooks) scratch = _make_scratch( in_features, features, groups=groups, expand=expand ) # Next-ViT-L on ImageNet-1K-6M (backbone) elif backbone == "levit_384": pretrained = _make_pretrained_levit_384( use_pretrained, hooks=hooks ) scratch = _make_scratch( [384, 512, 768], features, groups=groups, expand=expand ) # LeViT 384 (backbone) elif backbone == "vitl16_384": pretrained = _make_pretrained_vitl16_384( use_pretrained, hooks=hooks, use_readout=use_readout ) scratch = _make_scratch( [256, 512, 1024, 1024], features, groups=groups, expand=expand ) # ViT-L/16 - 85.0% Top1 (backbone) elif backbone == "vitb_rn50_384": pretrained = _make_pretrained_vitb_rn50_384( use_pretrained, hooks=hooks, use_vit_only=use_vit_only, use_readout=use_readout, ) scratch = _make_scratch( [256, 512, 768, 768], features, groups=groups, expand=expand ) # ViT-H/16 - 85.0% Top1 (backbone) elif backbone == "vitb16_384": pretrained = _make_pretrained_vitb16_384( use_pretrained, hooks=hooks, use_readout=use_readout ) scratch = _make_scratch( [96, 192, 384, 768], features, groups=groups, expand=expand ) # ViT-B/16 - 84.6% Top1 (backbone) elif backbone == "resnext101_wsl": pretrained = _make_pretrained_resnext101_wsl(use_pretrained) scratch = _make_scratch([256, 512, 1024, 2048], features, groups=groups, expand=expand) # efficientnet_lite3 elif backbone == "efficientnet_lite3": pretrained = _make_pretrained_efficientnet_lite3(use_pretrained, exportable=exportable) scratch = _make_scratch([32, 48, 136, 384], features, groups=groups, expand=expand) # efficientnet_lite3 else: print(f"Backbone '{backbone}' not implemented") assert False return pretrained, scratch
null
6,389
import cv2 import torch from midas.dpt_depth import DPTDepthModel from midas.midas_net import MidasNet from midas.midas_net_custom import MidasNet_small from midas.transforms import Resize, NormalizeImage, PrepareForNet from torchvision.transforms import Compose The provided code snippet includes necessary dependencies for implementing the `load_model` function. Write a Python function `def load_model(device, model_path, model_type="dpt_large_384", optimize=True, height=None, square=False)` to solve the following problem: Load the specified network. Args: device (device): the torch device used model_path (str): path to saved model model_type (str): the type of the model to be loaded optimize (bool): optimize the model to half-integer on CUDA? height (int): inference encoder image height square (bool): resize to a square resolution? Returns: The loaded network, the transform which prepares images as input to the network and the dimensions of the network input Here is the function: def load_model(device, model_path, model_type="dpt_large_384", optimize=True, height=None, square=False): """Load the specified network. Args: device (device): the torch device used model_path (str): path to saved model model_type (str): the type of the model to be loaded optimize (bool): optimize the model to half-integer on CUDA? height (int): inference encoder image height square (bool): resize to a square resolution? Returns: The loaded network, the transform which prepares images as input to the network and the dimensions of the network input """ if "openvino" in model_type: from openvino.runtime import Core keep_aspect_ratio = not square if model_type == "dpt_beit_large_512": model = DPTDepthModel( path=model_path, backbone="beitl16_512", non_negative=True, ) net_w, net_h = 512, 512 resize_mode = "minimal" normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) elif model_type == "dpt_beit_large_384": model = DPTDepthModel( path=model_path, backbone="beitl16_384", non_negative=True, ) net_w, net_h = 384, 384 resize_mode = "minimal" normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) elif model_type == "dpt_beit_base_384": model = DPTDepthModel( path=model_path, backbone="beitb16_384", non_negative=True, ) net_w, net_h = 384, 384 resize_mode = "minimal" normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) elif model_type == "dpt_swin2_large_384": model = DPTDepthModel( path=model_path, backbone="swin2l24_384", non_negative=True, ) net_w, net_h = 384, 384 keep_aspect_ratio = False resize_mode = "minimal" normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) elif model_type == "dpt_swin2_base_384": model = DPTDepthModel( path=model_path, backbone="swin2b24_384", non_negative=True, ) net_w, net_h = 384, 384 keep_aspect_ratio = False resize_mode = "minimal" normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) elif model_type == "dpt_swin2_tiny_256": model = DPTDepthModel( path=model_path, backbone="swin2t16_256", non_negative=True, ) net_w, net_h = 256, 256 keep_aspect_ratio = False resize_mode = "minimal" normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) elif model_type == "dpt_swin_large_384": model = DPTDepthModel( path=model_path, backbone="swinl12_384", non_negative=True, ) net_w, net_h = 384, 384 keep_aspect_ratio = False resize_mode = "minimal" normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) elif model_type == "dpt_next_vit_large_384": model = DPTDepthModel( path=model_path, backbone="next_vit_large_6m", non_negative=True, ) net_w, net_h = 384, 384 resize_mode = "minimal" normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) # We change the notation from dpt_levit_224 (MiDaS notation) to levit_384 (timm notation) here, where the 224 refers # to the resolution 224x224 used by LeViT and 384 is the first entry of the embed_dim, see _cfg and model_cfgs of # https://github.com/rwightman/pytorch-image-models/blob/main/timm/models/levit.py # (commit id: 927f031293a30afb940fff0bee34b85d9c059b0e) elif model_type == "dpt_levit_224": model = DPTDepthModel( path=model_path, backbone="levit_384", non_negative=True, head_features_1=64, head_features_2=8, ) net_w, net_h = 224, 224 keep_aspect_ratio = False resize_mode = "minimal" normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) elif model_type == "dpt_large_384": model = DPTDepthModel( path=model_path, backbone="vitl16_384", non_negative=True, ) net_w, net_h = 384, 384 resize_mode = "minimal" normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) elif model_type == "dpt_hybrid_384": model = DPTDepthModel( path=model_path, backbone="vitb_rn50_384", non_negative=True, ) net_w, net_h = 384, 384 resize_mode = "minimal" normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) elif model_type == "midas_v21_384": model = MidasNet(model_path, non_negative=True) net_w, net_h = 384, 384 resize_mode = "upper_bound" normalization = NormalizeImage( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] ) elif model_type == "midas_v21_small_256": model = MidasNet_small(model_path, features=64, backbone="efficientnet_lite3", exportable=True, non_negative=True, blocks={'expand': True}) net_w, net_h = 256, 256 resize_mode = "upper_bound" normalization = NormalizeImage( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] ) elif model_type == "openvino_midas_v21_small_256": ie = Core() uncompiled_model = ie.read_model(model=model_path) model = ie.compile_model(uncompiled_model, "CPU") net_w, net_h = 256, 256 resize_mode = "upper_bound" normalization = NormalizeImage( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] ) else: print(f"model_type '{model_type}' not implemented, use: --model_type large") assert False if not "openvino" in model_type: print("Model loaded, number of parameters = {:.0f}M".format(sum(p.numel() for p in model.parameters()) / 1e6)) else: print("Model loaded, optimized with OpenVINO") if "openvino" in model_type: keep_aspect_ratio = False if height is not None: net_w, net_h = height, height transform = Compose( [ Resize( net_w, net_h, resize_target=None, keep_aspect_ratio=keep_aspect_ratio, ensure_multiple_of=32, resize_method=resize_mode, image_interpolation_method=cv2.INTER_CUBIC, ), normalization, PrepareForNet(), ] ) if not "openvino" in model_type: model.eval() if optimize and (device == torch.device("cuda")): if not "openvino" in model_type: model = model.to(memory_format=torch.channels_last) model = model.half() else: print("Error: OpenVINO models are already optimized. No optimization to half-float possible.") exit() if not "openvino" in model_type: model.to(device) return model, transform, net_w, net_h
Load the specified network. Args: device (device): the torch device used model_path (str): path to saved model model_type (str): the type of the model to be loaded optimize (bool): optimize the model to half-integer on CUDA? height (int): inference encoder image height square (bool): resize to a square resolution? Returns: The loaded network, the transform which prepares images as input to the network and the dimensions of the network input
6,390
import torch import torch.nn as nn from .base_model import BaseModel from .blocks import FeatureFusionBlock, FeatureFusionBlock_custom, Interpolate, _make_encoder def fuse_model(m): prev_previous_type = nn.Identity() prev_previous_name = '' previous_type = nn.Identity() previous_name = '' for name, module in m.named_modules(): if prev_previous_type == nn.Conv2d and previous_type == nn.BatchNorm2d and type(module) == nn.ReLU: # print("FUSED ", prev_previous_name, previous_name, name) torch.quantization.fuse_modules(m, [prev_previous_name, previous_name, name], inplace=True) elif prev_previous_type == nn.Conv2d and previous_type == nn.BatchNorm2d: # print("FUSED ", prev_previous_name, previous_name) torch.quantization.fuse_modules(m, [prev_previous_name, previous_name], inplace=True) # elif previous_type == nn.Conv2d and type(module) == nn.ReLU: # print("FUSED ", previous_name, name) # torch.quantization.fuse_modules(m, [previous_name, name], inplace=True) prev_previous_type = previous_type prev_previous_name = previous_name previous_type = type(module) previous_name = name
null
6,391
import numpy as np import random import torch The provided code snippet includes necessary dependencies for implementing the `seed_all` function. Write a Python function `def seed_all(seed: int = 0)` to solve the following problem: Set random seeds of all components. Here is the function: def seed_all(seed: int = 0): """ Set random seeds of all components. """ random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed)
Set random seeds of all components.
6,392
import torch import math bs_search_table = [ # tested on A100-PCIE-80GB {"res": 768, "total_vram": 79, "bs": 35}, {"res": 1024, "total_vram": 79, "bs": 20}, # tested on A100-PCIE-40GB {"res": 768, "total_vram": 39, "bs": 15}, {"res": 1024, "total_vram": 39, "bs": 8}, # tested on RTX3090, RTX4090 {"res": 512, "total_vram": 23, "bs": 20}, {"res": 768, "total_vram": 23, "bs": 7}, {"res": 1024, "total_vram": 23, "bs": 3}, # tested on GTX1080Ti {"res": 512, "total_vram": 10, "bs": 5}, {"res": 768, "total_vram": 10, "bs": 2}, ] The provided code snippet includes necessary dependencies for implementing the `find_batch_size` function. Write a Python function `def find_batch_size(ensemble_size: int, input_res: int) -> int` to solve the following problem: Automatically search for suitable operating batch size. Args: ensemble_size (int): Number of predictions to be ensembled input_res (int): Operating resolution of the input image. Returns: int: Operating batch size Here is the function: def find_batch_size(ensemble_size: int, input_res: int) -> int: """ Automatically search for suitable operating batch size. Args: ensemble_size (int): Number of predictions to be ensembled input_res (int): Operating resolution of the input image. Returns: int: Operating batch size """ if not torch.cuda.is_available(): return 1 total_vram = torch.cuda.mem_get_info()[1] / 1024.0**3 for settings in sorted(bs_search_table, key=lambda k: (k["res"], -k["total_vram"])): if input_res <= settings["res"] and total_vram >= settings["total_vram"]: bs = settings["bs"] if bs > ensemble_size: bs = ensemble_size elif bs > math.ceil(ensemble_size / 2) and bs < ensemble_size: bs = math.ceil(ensemble_size / 2) return bs return 1
Automatically search for suitable operating batch size. Args: ensemble_size (int): Number of predictions to be ensembled input_res (int): Operating resolution of the input image. Returns: int: Operating batch size
6,393
import numpy as np import torch from scipy.optimize import minimize def inter_distances(tensors: torch.Tensor): """ To calculate the distance between each two depth maps. """ distances = [] for i, j in torch.combinations(torch.arange(tensors.shape[0])): arr1 = tensors[i : i + 1] arr2 = tensors[j : j + 1] distances.append(arr1 - arr2) dist = torch.concatenate(distances, dim=0) return dist The provided code snippet includes necessary dependencies for implementing the `ensemble_depths` function. Write a Python function `def ensemble_depths( input_images: torch.Tensor, regularizer_strength: float = 0.02, max_iter: int = 2, tol: float = 1e-3, reduction: str = "median", max_res: int = None, )` to solve the following problem: To ensemble multiple affine-invariant depth images (up to scale and shift), by aligning estimating the scale and shift Here is the function: def ensemble_depths( input_images: torch.Tensor, regularizer_strength: float = 0.02, max_iter: int = 2, tol: float = 1e-3, reduction: str = "median", max_res: int = None, ): """ To ensemble multiple affine-invariant depth images (up to scale and shift), by aligning estimating the scale and shift """ device = input_images.device dtype = np.float32 original_input = input_images.clone() n_img = input_images.shape[0] ori_shape = input_images.shape if max_res is not None: scale_factor = torch.min(max_res / torch.tensor(ori_shape[-2:])) if scale_factor < 1: downscaler = torch.nn.Upsample(scale_factor=scale_factor, mode="nearest") input_images = downscaler(torch.from_numpy(input_images)).numpy() # init guess _min = np.min(input_images.reshape((n_img, -1)).cpu().numpy(), axis=1) _max = np.max(input_images.reshape((n_img, -1)).cpu().numpy(), axis=1) s_init = 1.0 / (_max - _min).reshape((-1, 1, 1)) t_init = (-1 * s_init.flatten() * _min.flatten()).reshape((-1, 1, 1)) x = np.concatenate([s_init, t_init]).reshape(-1) input_images = input_images.to(device) # objective function def closure(x): x = x.astype(dtype) l = len(x) s = x[: int(l / 2)] t = x[int(l / 2) :] s = torch.from_numpy(s).to(device) t = torch.from_numpy(t).to(device) transformed_arrays = input_images * s.view((-1, 1, 1)) + t.view((-1, 1, 1)) dists = inter_distances(transformed_arrays) sqrt_dist = torch.sqrt(torch.mean(dists**2)) if "mean" == reduction: pred = torch.mean(transformed_arrays, dim=0) elif "median" == reduction: pred = torch.median(transformed_arrays, dim=0).values else: raise ValueError near_err = torch.sqrt((0 - torch.min(pred)) ** 2) far_err = torch.sqrt((1 - torch.max(pred)) ** 2) err = sqrt_dist + (near_err + far_err) * regularizer_strength err = err.detach().cpu().numpy() return err res = minimize( closure, x, method="BFGS", tol=tol, options={"maxiter": max_iter, "disp": False} ) x = res.x x = x.astype(dtype) l = len(x) s = x[: int(l / 2)] t = x[int(l / 2) :] # Prediction s = torch.from_numpy(s).to(device) t = torch.from_numpy(t).to(device) transformed_arrays = original_input * s.view(-1, 1, 1) + t.view(-1, 1, 1) if "mean" == reduction: aligned_images = torch.mean(transformed_arrays, dim=0) std = torch.std(transformed_arrays, dim=0) uncertainty = std elif "median" == reduction: aligned_images = torch.median(transformed_arrays, dim=0).values # MAD (median absolute deviation) as uncertainty indicator abs_dev = torch.abs(transformed_arrays - aligned_images) mad = torch.median(abs_dev, dim=0).values uncertainty = mad else: raise ValueError(f"Unknown reduction method: {reduction}") # Scale and shift to [0, 1] _min = torch.min(aligned_images) _max = torch.max(aligned_images) aligned_images = (aligned_images - _min) / (_max - _min) uncertainty /= _max - _min return aligned_images, uncertainty
To ensemble multiple affine-invariant depth images (up to scale and shift), by aligning estimating the scale and shift
6,394
import matplotlib import numpy as np import torch from PIL import Image The provided code snippet includes necessary dependencies for implementing the `colorize_depth_maps` function. Write a Python function `def colorize_depth_maps( depth_map, min_depth, max_depth, cmap="Spectral", valid_mask=None )` to solve the following problem: Colorize depth maps. Here is the function: def colorize_depth_maps( depth_map, min_depth, max_depth, cmap="Spectral", valid_mask=None ): """ Colorize depth maps. """ assert len(depth_map.shape) >= 2, "Invalid dimension" if isinstance(depth_map, torch.Tensor): depth = depth_map.detach().clone().squeeze().numpy() elif isinstance(depth_map, np.ndarray): depth = depth_map.copy().squeeze() # reshape to [ (B,) H, W ] if depth.ndim < 3: depth = depth[np.newaxis, :, :] # colorize cm = matplotlib.colormaps[cmap] depth = ((depth - min_depth) / (max_depth - min_depth)).clip(0, 1) img_colored_np = cm(depth, bytes=False)[:, :, :, 0:3] # value from 0 to 1 img_colored_np = np.rollaxis(img_colored_np, 3, 1) if valid_mask is not None: if isinstance(depth_map, torch.Tensor): valid_mask = valid_mask.detach().numpy() valid_mask = valid_mask.squeeze() # [H, W] or [B, H, W] if valid_mask.ndim < 3: valid_mask = valid_mask[np.newaxis, np.newaxis, :, :] else: valid_mask = valid_mask[:, np.newaxis, :, :] valid_mask = np.repeat(valid_mask, 3, axis=1) img_colored_np[~valid_mask] = 0 if isinstance(depth_map, torch.Tensor): img_colored = torch.from_numpy(img_colored_np).float() elif isinstance(depth_map, np.ndarray): img_colored = img_colored_np return img_colored
Colorize depth maps.
6,395
import matplotlib import numpy as np import torch from PIL import Image def chw2hwc(chw): assert 3 == len(chw.shape) if isinstance(chw, torch.Tensor): hwc = torch.permute(chw, (1, 2, 0)) elif isinstance(chw, np.ndarray): hwc = np.moveaxis(chw, 0, -1) return hwc
null
6,396
import matplotlib import numpy as np import torch from PIL import Image The provided code snippet includes necessary dependencies for implementing the `resize_max_res` function. Write a Python function `def resize_max_res(img: Image.Image, max_edge_resolution: int) -> Image.Image` to solve the following problem: Resize image to limit maximum edge length while keeping aspect ratio Args: img (Image.Image): Image to be resized max_edge_resolution (int): Maximum edge length (px). Returns: Image.Image: Resized image. Here is the function: def resize_max_res(img: Image.Image, max_edge_resolution: int) -> Image.Image: """ Resize image to limit maximum edge length while keeping aspect ratio Args: img (Image.Image): Image to be resized max_edge_resolution (int): Maximum edge length (px). Returns: Image.Image: Resized image. """ original_width, original_height = img.size downscale_factor = min( max_edge_resolution / original_width, max_edge_resolution / original_height ) new_width = int(original_width * downscale_factor) new_height = int(original_height * downscale_factor) resized_img = img.resize((new_width, new_height)) return resized_img
Resize image to limit maximum edge length while keeping aspect ratio Args: img (Image.Image): Image to be resized max_edge_resolution (int): Maximum edge length (px). Returns: Image.Image: Resized image.
6,397
import launch import platform import sys import importlib.metadata if not launch.is_installed('packaging'): launch.run_pip("install packaging", "packaging requirement for depthmap script") from packaging.version import Version if not launch.is_installed("moviepy"): launch.run_pip('install "moviepy==1.0.2"', "moviepy requirement for depthmap script") try: # Dirty hack to not reinstall every time importlib_metadata.version('imageio-ffmpeg') except: ensure('imageio-ffmpeg') if not launch.is_installed("networkx"): launch.run_pip('install install "networkx==2.5"', "networkx requirement for depthmap script") def ensure(module_name, min_version=None): if launch.is_installed(module_name): if min_version is None or Version(importlib_metadata.version(module_name)) >= Version(min_version): return requirement = f'{module_name}>={min_version}' if min_version is not None else module_name cmd = f'install "{requirement}"' msg = f'{requirement} requirement for depthmap script' launch.run_pip(cmd, msg)
null
6,398
import launch import platform import sys import importlib.metadata if not launch.is_installed('packaging'): launch.run_pip("install packaging", "packaging requirement for depthmap script") from packaging.version import Version if not launch.is_installed("moviepy"): launch.run_pip('install "moviepy==1.0.2"', "moviepy requirement for depthmap script") if not launch.is_installed("networkx"): launch.run_pip('install install "networkx==2.5"', "networkx requirement for depthmap script") def get_installed_version(package: str): try: return importlib.metadata.version(package) except Exception: return None def try_install_from_wheel(pkg_name: str, wheel_url: str): if get_installed_version(pkg_name) is not None: return try: launch.run_pip(f"install {wheel_url}", f" {pkg_name} requirement for depthmap script") except Exception as e: print('Failed to install wheel for Depth Anything support. It won\'t work.')
null
6,399
import os import numpy as np from fastapi import FastAPI, Body from fastapi.exceptions import HTTPException from PIL import Image import gradio as gr from typing import Dict, List from modules.api import api from src.core import core_generation_funnel, run_makevideo from src.misc import SCRIPT_VERSION from src import backbone from src.common_constants import GenerationOptions as go def encode_to_base64(image): if type(image) is str: return image elif type(image) is Image.Image: return api.encode_pil_to_base64(image) elif type(image) is np.ndarray: return encode_np_to_base64(image) else: return "" def to_base64_PIL(encoding: str): return Image.fromarray(np.array(api.decode_base64_to_image(encoding)).astype('uint8')) def core_generation_funnel(outpath, inputimages, inputdepthmaps, inputnames, inp, ops=None): if len(inputimages) == 0 or inputimages[0] is None: return if inputdepthmaps is None or len(inputdepthmaps) == 0: inputdepthmaps: list[Image] = [None for _ in range(len(inputimages))] inputdepthmaps_complete = all([x is not None for x in inputdepthmaps]) inp = CoreGenerationFunnelInp(inp) if ops is None: ops = backbone.gather_ops() model_holder.update_settings(**ops) # TODO: ideally, run_depthmap should not save meshes - that makes the function not pure print(SCRIPT_FULL_NAME) backbone.unload_sd_model() # TODO: this still should not be here background_removed_images = [] # remove on base image before depth calculation if inp[go.GEN_REMBG]: if inp[go.PRE_DEPTH_BACKGROUND_REMOVAL]: inputimages = batched_background_removal(inputimages, inp[go.REMBG_MODEL]) background_removed_images = inputimages else: background_removed_images = batched_background_removal(inputimages, inp[go.REMBG_MODEL]) # init torch device if inp[go.COMPUTE_DEVICE] == 'GPU': if torch.cuda.is_available(): device = torch.device("cuda") else: print('WARNING: Cuda device was not found, cpu will be used') device = torch.device("cpu") else: device = torch.device("cpu") print("device: %s" % device) # TODO: This should not be here inpaint_imgs = [] inpaint_depths = [] try: if not inputdepthmaps_complete: print("Loading model(s) ..") model_holder.ensure_models(inp[go.MODEL_TYPE], device, inp[go.BOOST]) print("Computing output(s) ..") # iterate over input images for count in trange(0, len(inputimages)): # Convert single channel input (PIL) images to rgb if inputimages[count].mode == 'I': inputimages[count].point(lambda p: p * 0.0039063096, mode='RGB') inputimages[count] = inputimages[count].convert('RGB') raw_prediction = None """Raw prediction, as returned by a model. None if input depthmap is used.""" raw_prediction_invert = False """True if near=dark on raw_prediction""" out = None if inputdepthmaps is not None and inputdepthmaps[count] is not None: # use custom depthmap dp = inputdepthmaps[count] if isinstance(dp, Image.Image): if dp.width != inputimages[count].width or dp.height != inputimages[count].height: try: # LANCZOS may fail on some formats dp = dp.resize((inputimages[count].width, inputimages[count].height), Image.Resampling.LANCZOS) except: dp = dp.resize((inputimages[count].width, inputimages[count].height)) # Trying desperately to rescale image to [0;1) without actually normalizing it # Normalizing is avoided, because we want to preserve the scale of the original depthmaps # (batch mode, video mode). if len(dp.getbands()) == 1: out = np.asarray(dp, dtype="float") out_max = out.max() if out_max < 256: bit_depth = 8 elif out_max < 65536: bit_depth = 16 else: bit_depth = 32 out /= 2.0 ** bit_depth else: out = np.asarray(dp, dtype="float")[:, :, 0] out /= 256.0 else: # Should be in interval [0; 1], values outside of this range will be clipped. out = np.asarray(dp, dtype="float") assert inputimages[count].height == out.shape[0], "Custom depthmap height mismatch" assert inputimages[count].width == out.shape[1], "Custom depthmap width mismatch" else: # override net size (size may be different for different images) if inp[go.NET_SIZE_MATCH]: # Round up to a multiple of 32 to avoid potential issues net_width = (inputimages[count].width + 31) // 32 * 32 net_height = (inputimages[count].height + 31) // 32 * 32 else: net_width = inp[go.NET_WIDTH] net_height = inp[go.NET_HEIGHT] raw_prediction, raw_prediction_invert = \ model_holder.get_raw_prediction(inputimages[count], net_width, net_height) # output if abs(raw_prediction.max() - raw_prediction.min()) > np.finfo("float").eps: out = np.copy(raw_prediction) # TODO: some models may output negative values, maybe these should be clamped to zero. if raw_prediction_invert: out *= -1 if inp[go.DO_OUTPUT_DEPTH_PREDICTION]: yield count, 'depth_prediction', np.copy(out) if inp[go.CLIPDEPTH]: if inp[go.CLIPDEPTH_MODE] == 'Range': out = (out - out.min()) / (out.max() - out.min()) # normalize to [0; 1] out = np.clip(out, inp[go.CLIPDEPTH_FAR], inp[go.CLIPDEPTH_NEAR]) elif inp[go.CLIPDEPTH_MODE] == 'Outliers': fb, nb = np.percentile(out, [inp[go.CLIPDEPTH_FAR] * 100.0, inp[go.CLIPDEPTH_NEAR] * 100.0]) out = np.clip(out, fb, nb) out = (out - out.min()) / (out.max() - out.min()) # normalize to [0; 1] else: # Regretfully, the depthmap is broken and will be replaced with a black image out = np.zeros(raw_prediction.shape) # Maybe we should not use img_output for everything, since we get better accuracy from # the raw_prediction. However, it is not always supported. We maybe would like to achieve # reproducibility, so depthmap of the image should be the same as generating the depthmap one more time. img_output = convert_to_i16(out) """Depthmap (near=bright), as uint16""" # if 3dinpainting, store maps for processing in second pass if inp[go.GEN_INPAINTED_MESH]: inpaint_imgs.append(inputimages[count]) inpaint_depths.append(img_output) # applying background masks after depth if inp[go.GEN_REMBG]: print('applying background masks') background_removed_image = background_removed_images[count] # maybe a threshold cut would be better on the line below. background_removed_array = np.array(background_removed_image) bg_mask = (background_removed_array[:, :, 0] == 0) & (background_removed_array[:, :, 1] == 0) & ( background_removed_array[:, :, 2] == 0) & (background_removed_array[:, :, 3] <= 0.2) img_output[bg_mask] = 0 # far value yield count, 'background_removed', background_removed_image if inp[go.SAVE_BACKGROUND_REMOVAL_MASKS]: bg_array = (1 - bg_mask.astype('int8')) * 255 mask_array = np.stack((bg_array, bg_array, bg_array, bg_array), axis=2) mask_image = Image.fromarray(mask_array.astype(np.uint8)) yield count, 'foreground_mask', mask_image # A weird quirk: if user tries to save depthmap, whereas custom depthmap is used, # custom depthmap will be outputed if inp[go.DO_OUTPUT_DEPTH]: img_depth = cv2.bitwise_not(img_output) if inp[go.OUTPUT_DEPTH_INVERT] else img_output if inp[go.OUTPUT_DEPTH_COMBINE]: axis = 1 if inp[go.OUTPUT_DEPTH_COMBINE_AXIS] == 'Horizontal' else 0 img_concat = Image.fromarray(np.concatenate( (inputimages[count], convert_i16_to_rgb(img_depth, inputimages[count])), axis=axis)) yield count, 'concat_depth', img_concat else: yield count, 'depth', Image.fromarray(img_depth) if inp[go.GEN_STEREO]: # print("Generating stereoscopic image(s)..") stereoimages = create_stereoimages( inputimages[count], img_output, inp[go.STEREO_DIVERGENCE], inp[go.STEREO_SEPARATION], inp[go.STEREO_MODES], inp[go.STEREO_BALANCE], inp[go.STEREO_OFFSET_EXPONENT], inp[go.STEREO_FILL_ALGO]) for c in range(0, len(stereoimages)): yield count, inp[go.STEREO_MODES][c], stereoimages[c] if inp[go.GEN_NORMALMAP]: normalmap = create_normalmap( img_output, inp[go.NORMALMAP_PRE_BLUR_KERNEL] if inp[go.NORMALMAP_PRE_BLUR] else None, inp[go.NORMALMAP_SOBEL_KERNEL] if inp[go.NORMALMAP_SOBEL] else None, inp[go.NORMALMAP_POST_BLUR_KERNEL] if inp[go.NORMALMAP_POST_BLUR] else None, inp[go.NORMALMAP_INVERT] ) yield count, 'normalmap', normalmap if inp[go.GEN_HEATMAP]: from dzoedepth.utils.misc import colorize heatmap = Image.fromarray(colorize(img_output, cmap='inferno')) yield count, 'heatmap', heatmap # gen mesh if inp[go.GEN_SIMPLE_MESH]: print(f"\nGenerating (occluded) mesh ..") basename = 'depthmap' meshsimple_fi = get_uniquefn(outpath, basename, 'obj', 'simple') depthi = raw_prediction if raw_prediction is not None else out depthi_min, depthi_max = depthi.min(), depthi.max() # try to map output to sensible values for non zoedepth models, boost, or custom maps if inp[go.MODEL_TYPE] not in [7, 8, 9] or inp[go.BOOST] or inputdepthmaps[count] is not None: # invert if midas if inp[go.MODEL_TYPE] > 0 or inputdepthmaps[count] is not None: # TODO: Weird depthi = depthi_max - depthi + depthi_min depth_max = depthi.max() depth_min = depthi.min() # make positive if depthi_min < 0: depthi = depthi - depthi_min depth_max = depthi.max() depth_min = depthi.min() # scale down if depthi.max() > 10.0: depthi = 4.0 * (depthi - depthi_min) / (depthi_max - depthi_min) # offset depthi = depthi + 1.0 mesh = create_mesh(inputimages[count], depthi, keep_edges=not inp[go.SIMPLE_MESH_OCCLUDE], spherical=(inp[go.SIMPLE_MESH_SPHERICAL])) mesh.export(meshsimple_fi) yield count, 'simple_mesh', meshsimple_fi print("Computing output(s) done.") except Exception as e: import traceback if 'out of memory' in str(e).lower(): print(str(e)) suggestion = "out of GPU memory, could not generate depthmap! " \ "Here are some suggestions to work around this issue:\n" if inp[go.BOOST]: suggestion += " * Disable BOOST (generation will be faster, but the depthmap will be less detailed)\n" if backbone.USED_BACKBONE != backbone.BackboneType.STANDALONE: suggestion += " * Run DepthMap in the standalone mode - without launching the SD WebUI\n" if device != torch.device("cpu"): suggestion += " * Select CPU as the processing device (this will be slower)\n" if inp[go.MODEL_TYPE] != 6: suggestion +=\ " * Use a different model (generally, more memory-consuming models produce better depthmaps)\n" if not inp[go.BOOST]: suggestion += " * Reduce net size (this could reduce quality)\n" print('Fail.\n') raise Exception(suggestion) else: print('Fail.\n') raise e finally: if backbone.get_opt('depthmap_script_keepmodels', True): model_holder.offload() # Swap to CPU memory else: model_holder.unload_models() gc.collect() backbone.torch_gc() # TODO: This should not be here if inp[go.GEN_INPAINTED_MESH]: try: mesh_fi = run_3dphoto(device, inpaint_imgs, inpaint_depths, inputnames, outpath, inp[go.GEN_INPAINTED_MESH_DEMOS], 1, "mp4") yield 0, 'inpainted_mesh', mesh_fi except Exception as e: print(f'{str(e)}, some issue with generating inpainted mesh') backbone.reload_sd_model() print("All done.\n") def run_makevideo(fn_mesh, vid_numframes, vid_fps, vid_traj, vid_shift, vid_border, dolly, vid_format, vid_ssaa, outpath=None, basename=None): if len(fn_mesh) == 0 or not os.path.exists(fn_mesh): raise Exception("Could not open mesh.") vid_ssaa = int(vid_ssaa) # traj type if vid_traj == 0: vid_traj = ['straight-line'] elif vid_traj == 1: vid_traj = ['double-straight-line'] elif vid_traj == 2: vid_traj = ['circle'] num_fps = int(vid_fps) num_frames = int(vid_numframes) shifts = vid_shift.split(',') if len(shifts) != 3: raise Exception("Translate requires 3 elements.") x_shift_range = [float(shifts[0])] y_shift_range = [float(shifts[1])] z_shift_range = [float(shifts[2])] borders = vid_border.split(',') if len(borders) != 4: raise Exception("Crop Border requires 4 elements.") crop_border = [float(borders[0]), float(borders[1]), float(borders[2]), float(borders[3])] if not outpath: outpath = backbone.get_outpath() if not basename: # output path and filename mess .. basename = Path(fn_mesh).stem # unique filename basecount = backbone.get_next_sequence_number(outpath, basename) if basecount > 0: basecount = basecount - 1 fullfn = None for i in range(500): fn = f"{basecount + i:05}" if basename == '' else f"{basename}-{basecount + i:04}" fullfn = os.path.join(outpath, f"{fn}_." + vid_format) if not os.path.exists(fullfn): break basename = Path(fullfn).stem basename = basename[:-1] print("Loading mesh ..") fn_saved = run_3dphoto_videos(fn_mesh, basename, outpath, num_frames, num_fps, crop_border, vid_traj, x_shift_range, y_shift_range, z_shift_range, [''], dolly, vid_format, vid_ssaa) return fn_saved[-1], fn_saved[-1], '' SCRIPT_VERSION = "v0.4.6" def depth_api(_: gr.Blocks, app: FastAPI): @app.get("/depth/version") async def version(): return {"version": SCRIPT_VERSION} @app.get("/depth/get_options") async def get_options(): return {"options": sorted([x.name.lower() for x in go])} # TODO: some potential inputs not supported (like custom depthmaps) @app.post("/depth/generate") async def process( depth_input_images: List[str] = Body([], title='Input Images'), options: Dict[str, object] = Body("options", title='Generation options'), ): # TODO: restrict mesh options if len(depth_input_images) == 0: raise HTTPException(status_code=422, detail="No images supplied") print(f"Processing {str(len(depth_input_images))} images trough the API") pil_images = [] for input_image in depth_input_images: pil_images.append(to_base64_PIL(input_image)) outpath = backbone.get_outpath() gen_obj = core_generation_funnel(outpath, pil_images, None, None, options) results_based = [] for count, type, result in gen_obj: if not isinstance(result, Image.Image): continue results_based += [encode_to_base64(result)] return {"images": results_based, "info": "Success"} @app.post("/depth/generate/video") async def process_video( depth_input_images: List[str] = Body([], title='Input Images'), options: Dict[str, object] = Body("options", title='Generation options'), ): if len(depth_input_images) == 0: raise HTTPException(status_code=422, detail="No images supplied") print(f"Processing {str(len(depth_input_images))} images trough the API") available_models = { 'res101': 0, 'dpt_beit_large_512': 1, #midas 3.1 'dpt_beit_large_384': 2, #midas 3.1 'dpt_large_384': 3, #midas 3.0 'dpt_hybrid_384': 4, #midas 3.0 'midas_v21': 5, 'midas_v21_small': 6, 'zoedepth_n': 7, #indoor 'zoedepth_k': 8, #outdoor 'zoedepth_nk': 9, } model_type = options["model_type"] model_id = None if isinstance(model_type, str): # Check if the string is in the available_models dictionary if model_type in available_models: model_id = available_models[model_type] else: available_strings = list(available_models.keys()) raise HTTPException(status_code=400, detail={'error': 'Invalid model string', 'available_models': available_strings}) elif isinstance(model_type, int): model_id = model_type else: raise HTTPException(status_code=400, detail={'error': 'Invalid model parameter type'}) options["model_type"] = model_id video_parameters = options["video_parameters"] required_params = ["vid_numframes", "vid_fps", "vid_traj", "vid_shift", "vid_border", "dolly", "vid_format", "vid_ssaa", "output_filename"] missing_params = [param for param in required_params if param not in video_parameters] if missing_params: raise HTTPException(status_code=400, detail={'error': f"Missing required parameter(s): {', '.join(missing_params)}"}) vid_numframes = video_parameters["vid_numframes"] vid_fps = video_parameters["vid_fps"] vid_traj = video_parameters["vid_traj"] vid_shift = video_parameters["vid_shift"] vid_border = video_parameters["vid_border"] dolly = video_parameters["dolly"] vid_format = video_parameters["vid_format"] vid_ssaa = int(video_parameters["vid_ssaa"]) output_filename = video_parameters["output_filename"] output_path = os.path.dirname(output_filename) basename, extension = os.path.splitext(os.path.basename(output_filename)) # Comparing video_format with the extension if vid_format != extension[1:]: raise HTTPException(status_code=400, detail={'error': f"Video format '{vid_format}' does not match with the extension '{extension}'."}) pil_images = [] for input_image in depth_input_images: pil_images.append(to_base64_PIL(input_image)) outpath = backbone.get_outpath() mesh_fi_filename = video_parameters.get('mesh_fi_filename', None) if mesh_fi_filename and os.path.exists(mesh_fi_filename): mesh_fi = mesh_fi_filename print("Loaded existing mesh from: ", mesh_fi) else: # If there is no mesh file generate it. options["GEN_INPAINTED_MESH"] = True gen_obj = core_generation_funnel(outpath, pil_images, None, None, options) mesh_fi = None for count, type, result in gen_obj: if type == 'inpainted_mesh': mesh_fi = result break if mesh_fi: print("Created mesh in: ", mesh_fi) else: raise HTTPException(status_code=400, detail={'error': "The mesh has not been created"}) run_makevideo(mesh_fi, vid_numframes, vid_fps, vid_traj, vid_shift, vid_border, dolly, vid_format, vid_ssaa, output_path, basename) return {"info": "Success"}
null
6,400
import traceback import gradio as gr from modules import shared import modules.scripts as scripts from PIL import Image from src import backbone from src import common_ui from src.core import core_generation_funnel from src.gradio_args_transport import GradioComponentBundle from src.misc import * from modules import script_callbacks def on_ui_settings(): section = ('depthmap-script', "Depthmap extension") def add_option(name, default_value, description, name_prefix='depthmap_script'): shared.opts.add_option(f"{name_prefix}_{name}", shared.OptionInfo(default_value, description, section=section)) add_option('keepmodels', False, "Do not unload depth and pix2pix models.") add_option('boost_rmax', 1600, "Maximum wholesize for boost (Rmax)") add_option('marigold_ensembles', 5, "How many ensembles to use for Marigold") add_option('marigold_steps', 10, "How many denoising steps to use for Marigold") add_option('save_ply', False, "Save additional PLY file with 3D inpainted mesh.") add_option('show_3d', True, "Enable showing 3D Meshes in output tab. (Experimental)") add_option('show_3d_inpaint', True, "Also show 3D Inpainted Mesh in 3D Mesh output tab. (Experimental)") add_option('mesh_maxsize', 2048, "Max size for generating simple mesh.") add_option('gen_heatmap_from_ui', False, "Show an option to generate HeatMap in the UI") add_option('extra_stereomodes', False, "Enable more possible outputs for stereoimage generation")
null
6,401
import os import cv2 import numpy as np import torch from PIL import Image from torch.utils.data import DataLoader, Dataset from torchvision import transforms class VKITTI2(Dataset): def __init__(self, data_dir_root, do_kb_crop=True, split="test"): import glob # image paths are of the form <data_dir_root>/rgb/<scene>/<variant>/frames/<rgb,depth>/Camera<0,1>/rgb_{}.jpg self.image_files = glob.glob(os.path.join( data_dir_root, "rgb", "**", "frames", "rgb", "Camera_0", '*.jpg'), recursive=True) self.depth_files = [r.replace("/rgb/", "/depth/").replace( "rgb_", "depth_").replace(".jpg", ".png") for r in self.image_files] self.do_kb_crop = True self.transform = ToTensor() # If train test split is not created, then create one. # Split is such that 8% of the frames from each scene are used for testing. if not os.path.exists(os.path.join(data_dir_root, "train.txt")): import random scenes = set([os.path.basename(os.path.dirname( os.path.dirname(os.path.dirname(f)))) for f in self.image_files]) train_files = [] test_files = [] for scene in scenes: scene_files = [f for f in self.image_files if os.path.basename( os.path.dirname(os.path.dirname(os.path.dirname(f)))) == scene] random.shuffle(scene_files) train_files.extend(scene_files[:int(len(scene_files) * 0.92)]) test_files.extend(scene_files[int(len(scene_files) * 0.92):]) with open(os.path.join(data_dir_root, "train.txt"), "w") as f: f.write("\n".join(train_files)) with open(os.path.join(data_dir_root, "test.txt"), "w") as f: f.write("\n".join(test_files)) if split == "train": with open(os.path.join(data_dir_root, "train.txt"), "r") as f: self.image_files = f.read().splitlines() self.depth_files = [r.replace("/rgb/", "/depth/").replace( "rgb_", "depth_").replace(".jpg", ".png") for r in self.image_files] elif split == "test": with open(os.path.join(data_dir_root, "test.txt"), "r") as f: self.image_files = f.read().splitlines() self.depth_files = [r.replace("/rgb/", "/depth/").replace( "rgb_", "depth_").replace(".jpg", ".png") for r in self.image_files] def __getitem__(self, idx): image_path = self.image_files[idx] depth_path = self.depth_files[idx] image = Image.open(image_path) # depth = Image.open(depth_path) depth = cv2.imread(depth_path, cv2.IMREAD_ANYCOLOR | cv2.IMREAD_ANYDEPTH) / 100.0 # cm to m depth = Image.fromarray(depth) # print("dpeth min max", depth.min(), depth.max()) # print(np.shape(image)) # print(np.shape(depth)) if self.do_kb_crop: if idx == 0: print("Using KB input crop") height = image.height width = image.width top_margin = int(height - 352) left_margin = int((width - 1216) / 2) depth = depth.crop( (left_margin, top_margin, left_margin + 1216, top_margin + 352)) image = image.crop( (left_margin, top_margin, left_margin + 1216, top_margin + 352)) # uv = uv[:, top_margin:top_margin + 352, left_margin:left_margin + 1216] image = np.asarray(image, dtype=np.float32) / 255.0 # depth = np.asarray(depth, dtype=np.uint16) /1. depth = np.asarray(depth, dtype=np.float32) / 1. depth[depth > 80] = -1 depth = depth[..., None] sample = dict(image=image, depth=depth) # return sample sample = self.transform(sample) if idx == 0: print(sample["image"].shape) return sample def __len__(self): return len(self.image_files) def get_vkitti2_loader(data_dir_root, batch_size=1, **kwargs): dataset = VKITTI2(data_dir_root) return DataLoader(dataset, batch_size, **kwargs)
null
6,402
import os import numpy as np import torch from PIL import Image from torch.utils.data import DataLoader, Dataset from torchvision import transforms class DDAD(Dataset): def __init__(self, data_dir_root, resize_shape): def __getitem__(self, idx): def __len__(self): def get_ddad_loader(data_dir_root, resize_shape, batch_size=1, **kwargs): dataset = DDAD(data_dir_root, resize_shape) return DataLoader(dataset, batch_size, **kwargs)
null
6,403
import math import random import cv2 import numpy as np The provided code snippet includes necessary dependencies for implementing the `apply_min_size` function. Write a Python function `def apply_min_size(sample, size, image_interpolation_method=cv2.INTER_AREA)` to solve the following problem: Rezise the sample to ensure the given size. Keeps aspect ratio. Args: sample (dict): sample size (tuple): image size Returns: tuple: new size Here is the function: def apply_min_size(sample, size, image_interpolation_method=cv2.INTER_AREA): """Rezise the sample to ensure the given size. Keeps aspect ratio. Args: sample (dict): sample size (tuple): image size Returns: tuple: new size """ shape = list(sample["disparity"].shape) if shape[0] >= size[0] and shape[1] >= size[1]: return sample scale = [0, 0] scale[0] = size[0] / shape[0] scale[1] = size[1] / shape[1] scale = max(scale) shape[0] = math.ceil(scale * shape[0]) shape[1] = math.ceil(scale * shape[1]) # resize sample["image"] = cv2.resize( sample["image"], tuple(shape[::-1]), interpolation=image_interpolation_method ) sample["disparity"] = cv2.resize( sample["disparity"], tuple(shape[::-1]), interpolation=cv2.INTER_NEAREST ) sample["mask"] = cv2.resize( sample["mask"].astype(np.float32), tuple(shape[::-1]), interpolation=cv2.INTER_NEAREST, ) sample["mask"] = sample["mask"].astype(bool) return tuple(shape)
Rezise the sample to ensure the given size. Keeps aspect ratio. Args: sample (dict): sample size (tuple): image size Returns: tuple: new size
6,404
import os import numpy as np import torch from PIL import Image from torch.utils.data import DataLoader, Dataset from torchvision import transforms class SunRGBD(Dataset): def __init__(self, data_dir_root): # test_file_dirs = loadmat(train_test_file)['alltest'].squeeze() # all_test = [t[0].replace("/n/fs/sun3d/data/", "") for t in test_file_dirs] # self.all_test = [os.path.join(data_dir_root, t) for t in all_test] import glob self.image_files = glob.glob( os.path.join(data_dir_root, 'rgb', 'rgb', '*')) self.depth_files = [ r.replace("rgb/rgb", "gt/gt").replace("jpg", "png") for r in self.image_files] self.transform = ToTensor() def __getitem__(self, idx): image_path = self.image_files[idx] depth_path = self.depth_files[idx] image = np.asarray(Image.open(image_path), dtype=np.float32) / 255.0 depth = np.asarray(Image.open(depth_path), dtype='uint16') / 1000.0 depth[depth > 8] = -1 depth = depth[..., None] return self.transform(dict(image=image, depth=depth)) def __len__(self): return len(self.image_files) def get_sunrgbd_loader(data_dir_root, batch_size=1, **kwargs): dataset = SunRGBD(data_dir_root) return DataLoader(dataset, batch_size, **kwargs)
null
6,405
import numpy as np from dataclasses import dataclass from typing import Tuple, List def get_white_border(rgb_image, value=255, **kwargs) -> CropParams: """Crops the white border of the RGB. Args: rgb: RGB image, shape (H, W, 3). Returns: Crop parameters. """ if value == 255: # assert range of values in rgb image is [0, 255] assert np.max(rgb_image) <= 255 and np.min(rgb_image) >= 0, "RGB image values are not in range [0, 255]." assert rgb_image.max() > 1, "RGB image values are not in range [0, 255]." elif value == 1: # assert range of values in rgb image is [0, 1] assert np.max(rgb_image) <= 1 and np.min(rgb_image) >= 0, "RGB image values are not in range [0, 1]." return get_border_params(rgb_image, value=value, **kwargs) def get_black_border(rgb_image, **kwargs) -> CropParams: """Crops the black border of the RGB. Args: rgb: RGB image, shape (H, W, 3). Returns: Crop parameters. """ return get_border_params(rgb_image, value=0, **kwargs) def crop_images(*images: np.ndarray, crop_params: CropParams) -> Tuple[np.ndarray]: """Crops the images according to the crop parameters. Args: images: RGB or depth images, shape (H, W, 3) or (H, W). crop_params: Crop parameters. Returns: Cropped images. """ return tuple(crop_image(image, crop_params) for image in images) The provided code snippet includes necessary dependencies for implementing the `crop_black_or_white_border` function. Write a Python function `def crop_black_or_white_border(rgb_image, *other_images: np.ndarray, tolerance=0.1, cut_off=20, level_diff_threshold=5) -> Tuple[np.ndarray]` to solve the following problem: Crops the white and black border of the RGB and depth images. Args: rgb: RGB image, shape (H, W, 3). This image is used to determine the border. other_images: The other images to crop according to the border of the RGB image. Returns: Cropped RGB and other images. Here is the function: def crop_black_or_white_border(rgb_image, *other_images: np.ndarray, tolerance=0.1, cut_off=20, level_diff_threshold=5) -> Tuple[np.ndarray]: """Crops the white and black border of the RGB and depth images. Args: rgb: RGB image, shape (H, W, 3). This image is used to determine the border. other_images: The other images to crop according to the border of the RGB image. Returns: Cropped RGB and other images. """ # crop black border crop_params = get_black_border(rgb_image, tolerance=tolerance, cut_off=cut_off, level_diff_threshold=level_diff_threshold) cropped_images = crop_images(rgb_image, *other_images, crop_params=crop_params) # crop white border crop_params = get_white_border(cropped_images[0], tolerance=tolerance, cut_off=cut_off, level_diff_threshold=level_diff_threshold) cropped_images = crop_images(*cropped_images, crop_params=crop_params) return cropped_images
Crops the white and black border of the RGB and depth images. Args: rgb: RGB image, shape (H, W, 3). This image is used to determine the border. other_images: The other images to crop according to the border of the RGB image. Returns: Cropped RGB and other images.
6,406
import torch from torch.utils.data import Dataset, DataLoader from torchvision import transforms import os from PIL import Image import numpy as np import cv2 class VKITTI(Dataset): def __init__(self, data_dir_root, do_kb_crop=True): import glob # image paths are of the form <data_dir_root>/{HR, LR}/<scene>/{color, depth_filled}/*.png self.image_files = glob.glob(os.path.join( data_dir_root, "test_color", '*.png')) self.depth_files = [r.replace("test_color", "test_depth") for r in self.image_files] self.do_kb_crop = True self.transform = ToTensor() def __getitem__(self, idx): image_path = self.image_files[idx] depth_path = self.depth_files[idx] image = Image.open(image_path) depth = Image.open(depth_path) depth = cv2.imread(depth_path, cv2.IMREAD_ANYCOLOR | cv2.IMREAD_ANYDEPTH) print("dpeth min max", depth.min(), depth.max()) # print(np.shape(image)) # print(np.shape(depth)) # depth[depth > 8] = -1 if self.do_kb_crop and False: height = image.height width = image.width top_margin = int(height - 352) left_margin = int((width - 1216) / 2) depth = depth.crop( (left_margin, top_margin, left_margin + 1216, top_margin + 352)) image = image.crop( (left_margin, top_margin, left_margin + 1216, top_margin + 352)) # uv = uv[:, top_margin:top_margin + 352, left_margin:left_margin + 1216] image = np.asarray(image, dtype=np.float32) / 255.0 # depth = np.asarray(depth, dtype=np.uint16) /1. depth = depth[..., None] sample = dict(image=image, depth=depth) # return sample sample = self.transform(sample) if idx == 0: print(sample["image"].shape) return sample def __len__(self): return len(self.image_files) def get_vkitti_loader(data_dir_root, batch_size=1, **kwargs): dataset = VKITTI(data_dir_root) return DataLoader(dataset, batch_size, **kwargs)
null
6,407
import os import numpy as np import torch from PIL import Image from torch.utils.data import DataLoader, Dataset from torchvision import transforms as T class iBims(Dataset): def __init__(self, config): root_folder = config.ibims_root with open(os.path.join(root_folder, "imagelist.txt"), 'r') as f: imglist = f.read().split() samples = [] for basename in imglist: img_path = os.path.join(root_folder, 'rgb', basename + ".png") depth_path = os.path.join(root_folder, 'depth', basename + ".png") valid_mask_path = os.path.join( root_folder, 'mask_invalid', basename+".png") transp_mask_path = os.path.join( root_folder, 'mask_transp', basename+".png") samples.append( (img_path, depth_path, valid_mask_path, transp_mask_path)) self.samples = samples # self.normalize = T.Normalize( # mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) self.normalize = lambda x : x def __getitem__(self, idx): img_path, depth_path, valid_mask_path, transp_mask_path = self.samples[idx] img = np.asarray(Image.open(img_path), dtype=np.float32) / 255.0 depth = np.asarray(Image.open(depth_path), dtype=np.uint16).astype('float')*50.0/65535 mask_valid = np.asarray(Image.open(valid_mask_path)) mask_transp = np.asarray(Image.open(transp_mask_path)) # depth = depth * mask_valid * mask_transp depth = np.where(mask_valid * mask_transp, depth, -1) img = torch.from_numpy(img).permute(2, 0, 1) img = self.normalize(img) depth = torch.from_numpy(depth).unsqueeze(0) return dict(image=img, depth=depth, image_path=img_path, depth_path=depth_path, dataset='ibims') def __len__(self): return len(self.samples) def get_ibims_loader(config, batch_size=1, **kwargs): dataloader = DataLoader(iBims(config), batch_size=batch_size, **kwargs) return dataloader
null
6,408
import glob import os import h5py import numpy as np import torch from PIL import Image from torch.utils.data import DataLoader, Dataset from torchvision import transforms def hypersim_distance_to_depth(npyDistance): intWidth, intHeight, fltFocal = 1024, 768, 886.81 npyImageplaneX = np.linspace((-0.5 * intWidth) + 0.5, (0.5 * intWidth) - 0.5, intWidth).reshape( 1, intWidth).repeat(intHeight, 0).astype(np.float32)[:, :, None] npyImageplaneY = np.linspace((-0.5 * intHeight) + 0.5, (0.5 * intHeight) - 0.5, intHeight).reshape(intHeight, 1).repeat(intWidth, 1).astype(np.float32)[:, :, None] npyImageplaneZ = np.full([intHeight, intWidth, 1], fltFocal, np.float32) npyImageplane = np.concatenate( [npyImageplaneX, npyImageplaneY, npyImageplaneZ], 2) npyDepth = npyDistance / np.linalg.norm(npyImageplane, 2, 2) * fltFocal return npyDepth
null
6,409
import glob import os import h5py import numpy as np import torch from PIL import Image from torch.utils.data import DataLoader, Dataset from torchvision import transforms class HyperSim(Dataset): def __init__(self, data_dir_root): # image paths are of the form <data_dir_root>/<scene>/images/scene_cam_#_final_preview/*.tonemap.jpg # depth paths are of the form <data_dir_root>/<scene>/images/scene_cam_#_final_preview/*.depth_meters.hdf5 self.image_files = glob.glob(os.path.join( data_dir_root, '*', 'images', 'scene_cam_*_final_preview', '*.tonemap.jpg')) self.depth_files = [r.replace("_final_preview", "_geometry_hdf5").replace( ".tonemap.jpg", ".depth_meters.hdf5") for r in self.image_files] self.transform = ToTensor() def __getitem__(self, idx): image_path = self.image_files[idx] depth_path = self.depth_files[idx] image = np.asarray(Image.open(image_path), dtype=np.float32) / 255.0 # depth from hdf5 depth_fd = h5py.File(depth_path, "r") # in meters (Euclidean distance) distance_meters = np.array(depth_fd['dataset']) depth = hypersim_distance_to_depth( distance_meters) # in meters (planar depth) # depth[depth > 8] = -1 depth = depth[..., None] sample = dict(image=image, depth=depth) sample = self.transform(sample) if idx == 0: print(sample["image"].shape) return sample def __len__(self): return len(self.image_files) def get_hypersim_loader(data_dir_root, batch_size=1, **kwargs): dataset = HyperSim(data_dir_root) return DataLoader(dataset, batch_size, **kwargs)
null
6,410
import os import numpy as np import torch from PIL import Image from torch.utils.data import DataLoader, Dataset from torchvision import transforms class DIODE(Dataset): def __init__(self, data_dir_root): import glob # image paths are of the form <data_dir_root>/scene_#/scan_#/*.png self.image_files = glob.glob( os.path.join(data_dir_root, '*', '*', '*.png')) self.depth_files = [r.replace(".png", "_depth.npy") for r in self.image_files] self.depth_mask_files = [ r.replace(".png", "_depth_mask.npy") for r in self.image_files] self.transform = ToTensor() def __getitem__(self, idx): image_path = self.image_files[idx] depth_path = self.depth_files[idx] depth_mask_path = self.depth_mask_files[idx] image = np.asarray(Image.open(image_path), dtype=np.float32) / 255.0 depth = np.load(depth_path) # in meters valid = np.load(depth_mask_path) # binary # depth[depth > 8] = -1 # depth = depth[..., None] sample = dict(image=image, depth=depth, valid=valid) # return sample sample = self.transform(sample) if idx == 0: print(sample["image"].shape) return sample def __len__(self): return len(self.image_files) def get_diode_loader(data_dir_root, batch_size=1, **kwargs): dataset = DIODE(data_dir_root) return DataLoader(dataset, batch_size, **kwargs)
null
6,411
import itertools import os import random import numpy as np import cv2 import torch import torch.nn as nn import torch.utils.data.distributed from zoedepth.utils.easydict import EasyDict as edict from PIL import Image, ImageOps from torch.utils.data import DataLoader, Dataset from torchvision import transforms from zoedepth.utils.config import change_dataset from .ddad import get_ddad_loader from .diml_indoor_test import get_diml_indoor_loader from .diml_outdoor_test import get_diml_outdoor_loader from .diode import get_diode_loader from .hypersim import get_hypersim_loader from .ibims import get_ibims_loader from .sun_rgbd_loader import get_sunrgbd_loader from .vkitti import get_vkitti_loader from .vkitti2 import get_vkitti2_loader from .preprocess import CropParams, get_white_border, get_black_border def _is_pil_image(img): return isinstance(img, Image.Image)
null
6,412
import itertools import os import random import numpy as np import cv2 import torch import torch.nn as nn import torch.utils.data.distributed from zoedepth.utils.easydict import EasyDict as edict from PIL import Image, ImageOps from torch.utils.data import DataLoader, Dataset from torchvision import transforms from zoedepth.utils.config import change_dataset from .ddad import get_ddad_loader from .diml_indoor_test import get_diml_indoor_loader from .diml_outdoor_test import get_diml_outdoor_loader from .diode import get_diode_loader from .hypersim import get_hypersim_loader from .ibims import get_ibims_loader from .sun_rgbd_loader import get_sunrgbd_loader from .vkitti import get_vkitti_loader from .vkitti2 import get_vkitti2_loader from .preprocess import CropParams, get_white_border, get_black_border def _is_numpy_image(img): return isinstance(img, np.ndarray) and (img.ndim in {2, 3})
null
6,413
import itertools import os import random import numpy as np import cv2 import torch import torch.nn as nn import torch.utils.data.distributed from zoedepth.utils.easydict import EasyDict as edict from PIL import Image, ImageOps from torch.utils.data import DataLoader, Dataset from torchvision import transforms from zoedepth.utils.config import change_dataset from .ddad import get_ddad_loader from .diml_indoor_test import get_diml_indoor_loader from .diml_outdoor_test import get_diml_outdoor_loader from .diode import get_diode_loader from .hypersim import get_hypersim_loader from .ibims import get_ibims_loader from .sun_rgbd_loader import get_sunrgbd_loader from .vkitti import get_vkitti_loader from .vkitti2 import get_vkitti2_loader from .preprocess import CropParams, get_white_border, get_black_border class ToTensor(object): def __init__(self, mode, do_normalize=False, size=None): self.mode = mode self.normalize = transforms.Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) if do_normalize else nn.Identity() self.size = size if size is not None: self.resize = transforms.Resize(size=size) else: self.resize = nn.Identity() def __call__(self, sample): image, focal = sample['image'], sample['focal'] image = self.to_tensor(image) image = self.normalize(image) image = self.resize(image) if self.mode == 'test': return {'image': image, 'focal': focal} depth = sample['depth'] if self.mode == 'train': depth = self.to_tensor(depth) return {**sample, 'image': image, 'depth': depth, 'focal': focal} else: has_valid_depth = sample['has_valid_depth'] image = self.resize(image) return {**sample, 'image': image, 'depth': depth, 'focal': focal, 'has_valid_depth': has_valid_depth, 'image_path': sample['image_path'], 'depth_path': sample['depth_path']} def to_tensor(self, pic): if not (_is_pil_image(pic) or _is_numpy_image(pic)): raise TypeError( 'pic should be PIL Image or ndarray. Got {}'.format(type(pic))) if isinstance(pic, np.ndarray): img = torch.from_numpy(pic.transpose((2, 0, 1))) return img # handle PIL Image if pic.mode == 'I': img = torch.from_numpy(np.array(pic, np.int32, copy=False)) elif pic.mode == 'I;16': img = torch.from_numpy(np.array(pic, np.int16, copy=False)) else: img = torch.ByteTensor( torch.ByteStorage.from_buffer(pic.tobytes())) # PIL image mode: 1, L, P, I, F, RGB, YCbCr, RGBA, CMYK if pic.mode == 'YCbCr': nchannel = 3 elif pic.mode == 'I;16': nchannel = 1 else: nchannel = len(pic.mode) img = img.view(pic.size[1], pic.size[0], nchannel) img = img.transpose(0, 1).transpose(0, 2).contiguous() if isinstance(img, torch.ByteTensor): return img.float() else: return img def preprocessing_transforms(mode, **kwargs): return transforms.Compose([ ToTensor(mode=mode, **kwargs) ])
null
6,414
import itertools import os import random import numpy as np import cv2 import torch import torch.nn as nn import torch.utils.data.distributed from zoedepth.utils.easydict import EasyDict as edict from PIL import Image, ImageOps from torch.utils.data import DataLoader, Dataset from torchvision import transforms from zoedepth.utils.config import change_dataset from .ddad import get_ddad_loader from .diml_indoor_test import get_diml_indoor_loader from .diml_outdoor_test import get_diml_outdoor_loader from .diode import get_diode_loader from .hypersim import get_hypersim_loader from .ibims import get_ibims_loader from .sun_rgbd_loader import get_sunrgbd_loader from .vkitti import get_vkitti_loader from .vkitti2 import get_vkitti2_loader from .preprocess import CropParams, get_white_border, get_black_border The provided code snippet includes necessary dependencies for implementing the `repetitive_roundrobin` function. Write a Python function `def repetitive_roundrobin(*iterables)` to solve the following problem: cycles through iterables but sample wise first yield first sample from first iterable then first sample from second iterable and so on then second sample from first iterable then second sample from second iterable and so on If one iterable is shorter than the others, it is repeated until all iterables are exhausted repetitive_roundrobin('ABC', 'D', 'EF') --> A D E B D F C D E Here is the function: def repetitive_roundrobin(*iterables): """ cycles through iterables but sample wise first yield first sample from first iterable then first sample from second iterable and so on then second sample from first iterable then second sample from second iterable and so on If one iterable is shorter than the others, it is repeated until all iterables are exhausted repetitive_roundrobin('ABC', 'D', 'EF') --> A D E B D F C D E """ # Repetitive roundrobin iterables_ = [iter(it) for it in iterables] exhausted = [False] * len(iterables) while not all(exhausted): for i, it in enumerate(iterables_): try: yield next(it) except StopIteration: exhausted[i] = True iterables_[i] = itertools.cycle(iterables[i]) # First elements may get repeated if one iterable is shorter than the others yield next(iterables_[i])
cycles through iterables but sample wise first yield first sample from first iterable then first sample from second iterable and so on then second sample from first iterable then second sample from second iterable and so on If one iterable is shorter than the others, it is repeated until all iterables are exhausted repetitive_roundrobin('ABC', 'D', 'EF') --> A D E B D F C D E
6,415
import itertools import os import random import numpy as np import cv2 import torch import torch.nn as nn import torch.utils.data.distributed from zoedepth.utils.easydict import EasyDict as edict from PIL import Image, ImageOps from torch.utils.data import DataLoader, Dataset from torchvision import transforms from zoedepth.utils.config import change_dataset from .ddad import get_ddad_loader from .diml_indoor_test import get_diml_indoor_loader from .diml_outdoor_test import get_diml_outdoor_loader from .diode import get_diode_loader from .hypersim import get_hypersim_loader from .ibims import get_ibims_loader from .sun_rgbd_loader import get_sunrgbd_loader from .vkitti import get_vkitti_loader from .vkitti2 import get_vkitti2_loader from .preprocess import CropParams, get_white_border, get_black_border def remove_leading_slash(s): if s[0] == '/' or s[0] == '\\': return s[1:] return s
null
6,416
import os import uuid import warnings from datetime import datetime as dt from typing import Dict import matplotlib.pyplot as plt import numpy as np import torch import torch.distributed as dist import torch.nn as nn import torch.optim as optim import wandb from tqdm import tqdm from zoedepth.utils.config import flatten from zoedepth.utils.misc import RunningAverageDict, colorize, colors def is_rank_zero(args): return args.rank == 0
null
6,417
import torch import torch.nn as nn import torch.nn.functional as F import torch.cuda.amp as amp import numpy as np def extract_key(prediction, key): if isinstance(prediction, dict): return prediction[key] return prediction
null
6,418
import torch import torch.nn as nn import torch.nn.functional as F import torch.cuda.amp as amp import numpy as np def grad(x): # x.shape : n, c, h, w diff_x = x[..., 1:, 1:] - x[..., 1:, :-1] diff_y = x[..., 1:, 1:] - x[..., :-1, 1:] mag = diff_x**2 + diff_y**2 # angle_ratio angle = torch.atan(diff_y / (diff_x + 1e-10)) return mag, angle
null
6,419
import torch import torch.nn as nn import torch.nn.functional as F import torch.cuda.amp as amp import numpy as np def grad_mask(mask): return mask[..., 1:, 1:] & mask[..., 1:, :-1] & mask[..., :-1, 1:]
null
6,420
import torch import torch.nn as nn import torch.nn.functional as F import torch.cuda.amp as amp import numpy as np def compute_scale_and_shift(prediction, target, mask): # system matrix: A = [[a_00, a_01], [a_10, a_11]] a_00 = torch.sum(mask * prediction * prediction, (1, 2)) a_01 = torch.sum(mask * prediction, (1, 2)) a_11 = torch.sum(mask, (1, 2)) # right hand side: b = [b_0, b_1] b_0 = torch.sum(mask * prediction * target, (1, 2)) b_1 = torch.sum(mask * target, (1, 2)) # solution: x = A^-1 . b = [[a_11, -a_01], [-a_10, a_00]] / (a_00 * a_11 - a_01 * a_10) . b x_0 = torch.zeros_like(b_0) x_1 = torch.zeros_like(b_1) det = a_00 * a_11 - a_01 * a_01 # A needs to be a positive definite matrix. valid = det > 0 x_0[valid] = (a_11[valid] * b_0[valid] - a_01[valid] * b_1[valid]) / det[valid] x_1[valid] = (-a_01[valid] * b_0[valid] + a_00[valid] * b_1[valid]) / det[valid] return x_0, x_1
null
6,421
from importlib import import_module The provided code snippet includes necessary dependencies for implementing the `get_trainer` function. Write a Python function `def get_trainer(config)` to solve the following problem: Builds and returns a trainer based on the config. Args: config (dict): the config dict (typically constructed using utils.config.get_config) config.trainer (str): the name of the trainer to use. The module named "{config.trainer}_trainer" must exist in trainers root module Raises: ValueError: If the specified trainer does not exist under trainers/ folder Returns: Trainer (inherited from zoedepth.trainers.BaseTrainer): The Trainer object Here is the function: def get_trainer(config): """Builds and returns a trainer based on the config. Args: config (dict): the config dict (typically constructed using utils.config.get_config) config.trainer (str): the name of the trainer to use. The module named "{config.trainer}_trainer" must exist in trainers root module Raises: ValueError: If the specified trainer does not exist under trainers/ folder Returns: Trainer (inherited from zoedepth.trainers.BaseTrainer): The Trainer object """ assert "trainer" in config and config.trainer is not None and config.trainer != '', "Trainer not specified. Config: {0}".format( config) try: Trainer = getattr(import_module( f"zoedepth.trainers.{config.trainer}_trainer"), 'Trainer') except ModuleNotFoundError as e: raise ValueError(f"Trainer {config.trainer}_trainer not found.") from e return Trainer
Builds and returns a trainer based on the config. Args: config (dict): the config dict (typically constructed using utils.config.get_config) config.trainer (str): the name of the trainer to use. The module named "{config.trainer}_trainer" must exist in trainers root module Raises: ValueError: If the specified trainer does not exist under trainers/ folder Returns: Trainer (inherited from zoedepth.trainers.BaseTrainer): The Trainer object
6,422
import torch import torch.nn as nn The provided code snippet includes necessary dependencies for implementing the `exp_attractor` function. Write a Python function `def exp_attractor(dx, alpha: float = 300, gamma: int = 2)` to solve the following problem: Exponential attractor: dc = exp(-alpha*|dx|^gamma) * dx , where dx = a - c, a = attractor point, c = bin center, dc = shift in bin centermmary for exp_attractor Args: dx (torch.Tensor): The difference tensor dx = Ai - Cj, where Ai is the attractor point and Cj is the bin center. alpha (float, optional): Proportional Attractor strength. Determines the absolute strength. Lower alpha = greater attraction. Defaults to 300. gamma (int, optional): Exponential Attractor strength. Determines the "region of influence" and indirectly number of bin centers affected. Lower gamma = farther reach. Defaults to 2. Returns: torch.Tensor : Delta shifts - dc; New bin centers = Old bin centers + dc Here is the function: def exp_attractor(dx, alpha: float = 300, gamma: int = 2): """Exponential attractor: dc = exp(-alpha*|dx|^gamma) * dx , where dx = a - c, a = attractor point, c = bin center, dc = shift in bin centermmary for exp_attractor Args: dx (torch.Tensor): The difference tensor dx = Ai - Cj, where Ai is the attractor point and Cj is the bin center. alpha (float, optional): Proportional Attractor strength. Determines the absolute strength. Lower alpha = greater attraction. Defaults to 300. gamma (int, optional): Exponential Attractor strength. Determines the "region of influence" and indirectly number of bin centers affected. Lower gamma = farther reach. Defaults to 2. Returns: torch.Tensor : Delta shifts - dc; New bin centers = Old bin centers + dc """ return torch.exp(-alpha*(torch.abs(dx)**gamma)) * (dx)
Exponential attractor: dc = exp(-alpha*|dx|^gamma) * dx , where dx = a - c, a = attractor point, c = bin center, dc = shift in bin centermmary for exp_attractor Args: dx (torch.Tensor): The difference tensor dx = Ai - Cj, where Ai is the attractor point and Cj is the bin center. alpha (float, optional): Proportional Attractor strength. Determines the absolute strength. Lower alpha = greater attraction. Defaults to 300. gamma (int, optional): Exponential Attractor strength. Determines the "region of influence" and indirectly number of bin centers affected. Lower gamma = farther reach. Defaults to 2. Returns: torch.Tensor : Delta shifts - dc; New bin centers = Old bin centers + dc
6,423
import torch import torch.nn as nn The provided code snippet includes necessary dependencies for implementing the `inv_attractor` function. Write a Python function `def inv_attractor(dx, alpha: float = 300, gamma: int = 2)` to solve the following problem: Inverse attractor: dc = dx / (1 + alpha*dx^gamma), where dx = a - c, a = attractor point, c = bin center, dc = shift in bin center This is the default one according to the accompanying paper. Args: dx (torch.Tensor): The difference tensor dx = Ai - Cj, where Ai is the attractor point and Cj is the bin center. alpha (float, optional): Proportional Attractor strength. Determines the absolute strength. Lower alpha = greater attraction. Defaults to 300. gamma (int, optional): Exponential Attractor strength. Determines the "region of influence" and indirectly number of bin centers affected. Lower gamma = farther reach. Defaults to 2. Returns: torch.Tensor: Delta shifts - dc; New bin centers = Old bin centers + dc Here is the function: def inv_attractor(dx, alpha: float = 300, gamma: int = 2): """Inverse attractor: dc = dx / (1 + alpha*dx^gamma), where dx = a - c, a = attractor point, c = bin center, dc = shift in bin center This is the default one according to the accompanying paper. Args: dx (torch.Tensor): The difference tensor dx = Ai - Cj, where Ai is the attractor point and Cj is the bin center. alpha (float, optional): Proportional Attractor strength. Determines the absolute strength. Lower alpha = greater attraction. Defaults to 300. gamma (int, optional): Exponential Attractor strength. Determines the "region of influence" and indirectly number of bin centers affected. Lower gamma = farther reach. Defaults to 2. Returns: torch.Tensor: Delta shifts - dc; New bin centers = Old bin centers + dc """ return dx.div(1+alpha*dx.pow(gamma))
Inverse attractor: dc = dx / (1 + alpha*dx^gamma), where dx = a - c, a = attractor point, c = bin center, dc = shift in bin center This is the default one according to the accompanying paper. Args: dx (torch.Tensor): The difference tensor dx = Ai - Cj, where Ai is the attractor point and Cj is the bin center. alpha (float, optional): Proportional Attractor strength. Determines the absolute strength. Lower alpha = greater attraction. Defaults to 300. gamma (int, optional): Exponential Attractor strength. Determines the "region of influence" and indirectly number of bin centers affected. Lower gamma = farther reach. Defaults to 2. Returns: torch.Tensor: Delta shifts - dc; New bin centers = Old bin centers + dc
6,424
import torch import torch.nn as nn The provided code snippet includes necessary dependencies for implementing the `log_binom` function. Write a Python function `def log_binom(n, k, eps=1e-7)` to solve the following problem: log(nCk) using stirling approximation Here is the function: def log_binom(n, k, eps=1e-7): """ log(nCk) using stirling approximation """ n = n + eps k = k + eps return n * torch.log(n) - k * torch.log(k) - (n-k) * torch.log(n-k+eps)
log(nCk) using stirling approximation
6,425
import torch def load_wts(model, checkpoint_path): ckpt = torch.load(checkpoint_path, map_location='cpu') return load_state_dict(model, ckpt) def load_state_dict_from_url(model, url, **kwargs): state_dict = torch.hub.load_state_dict_from_url(url, map_location='cpu', **kwargs) return load_state_dict(model, state_dict) The provided code snippet includes necessary dependencies for implementing the `load_state_from_resource` function. Write a Python function `def load_state_from_resource(model, resource: str)` to solve the following problem: Loads weights to the model from a given resource. A resource can be of following types: 1. URL. Prefixed with "url::" e.g. url::http(s)://url.resource.com/ckpt.pt 2. Local path. Prefixed with "local::" e.g. local::/path/to/ckpt.pt Args: model (torch.nn.Module): Model resource (str): resource string Returns: torch.nn.Module: Model with loaded weights Here is the function: def load_state_from_resource(model, resource: str): """Loads weights to the model from a given resource. A resource can be of following types: 1. URL. Prefixed with "url::" e.g. url::http(s)://url.resource.com/ckpt.pt 2. Local path. Prefixed with "local::" e.g. local::/path/to/ckpt.pt Args: model (torch.nn.Module): Model resource (str): resource string Returns: torch.nn.Module: Model with loaded weights """ print(f"Using pretrained resource {resource}") if resource.startswith('url::'): url = resource.split('url::')[1] return load_state_dict_from_url(model, url, progress=True) elif resource.startswith('local::'): path = resource.split('local::')[1] return load_wts(model, path) else: raise ValueError("Invalid resource type, only url:: and local:: are supported")
Loads weights to the model from a given resource. A resource can be of following types: 1. URL. Prefixed with "url::" e.g. url::http(s)://url.resource.com/ckpt.pt 2. Local path. Prefixed with "local::" e.g. local::/path/to/ckpt.pt Args: model (torch.nn.Module): Model resource (str): resource string Returns: torch.nn.Module: Model with loaded weights
6,426
import torch import torch.nn as nn import numpy as np from torchvision.transforms import Normalize The provided code snippet includes necessary dependencies for implementing the `denormalize` function. Write a Python function `def denormalize(x)` to solve the following problem: Reverses the imagenet normalization applied to the input. Args: x (torch.Tensor - shape(N,3,H,W)): input tensor Returns: torch.Tensor - shape(N,3,H,W): Denormalized input Here is the function: def denormalize(x): """Reverses the imagenet normalization applied to the input. Args: x (torch.Tensor - shape(N,3,H,W)): input tensor Returns: torch.Tensor - shape(N,3,H,W): Denormalized input """ mean = torch.Tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1).to(x.device) std = torch.Tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1).to(x.device) return x * std + mean
Reverses the imagenet normalization applied to the input. Args: x (torch.Tensor - shape(N,3,H,W)): input tensor Returns: torch.Tensor - shape(N,3,H,W): Denormalized input
6,427
import torch import torch.nn as nn import numpy as np from torchvision.transforms import Normalize def get_activation(name, bank): def hook(model, input, output): bank[name] = output return hook
null