MCPcopy Create free account
hub / github.com/InternRobotics/G2VLM / colorize_optimized

Function colorize_optimized

eval_code/recons/videodepth/utils.py:100–180  ·  view source on GitHub ↗
(
    x, cmap_name="jet", mask=None, value_range=None, append_cbar=False, cbar_in_image=False, cbar_precision=2
)

Source from the content-addressed store, hash-verified

98
99
100def colorize_optimized(
101 x, cmap_name="jet", mask=None, value_range=None, append_cbar=False, cbar_in_image=False, cbar_precision=2
102):
103 device = x.device
104 original_shape = x.shape
105 if x.dim() == 2:
106 x = x.unsqueeze(0)
107 B, H, W = x.shape
108
109 # deal with vmin/vmax
110 if value_range is not None:
111 vmin, vmax = value_range
112 vmin = torch.full((B,), vmin, device=device)
113 vmax = torch.full((B,), vmax, device=device)
114 else:
115 if mask is not None:
116 if mask.dim() == 2:
117 mask = mask.unsqueeze(0)
118 mask = mask.expand(B, H, W)
119 non_zero_mask = mask & (x != 0)
120 has_non_zero = non_zero_mask.reshape(B, -1).any(dim=1)
121
122 # min value of non-zero elements in the mask
123 non_zero_vmin = x.masked_fill(~non_zero_mask, float('inf')).view(B, -1).min(dim=1)[0]
124 # min value of all masked elements
125 mask_vmin = x.masked_fill(~mask, float('inf')).view(B, -1).min(dim=1)[0]
126 vmin = torch.where(has_non_zero, non_zero_vmin, mask_vmin)
127 # set unmasked values -> vmin
128 x = x.masked_fill(~mask, vmin.view(B, 1, 1))
129 # calculate vmax
130 vmax = x.masked_fill(~mask, float('-inf')).view(B, -1).max(dim=1)[0]
131 else:
132 # if no mask, use quantiles
133 x_flatten = x.view(B, -1)
134 vmin = torch.quantile(x_flatten, 0.01, dim=1)
135 vmax = torch.quantile(x_flatten, 1.0, dim=1) + 1e-6
136
137 # clip and normalize the input
138 x_clipped = torch.clamp(x, min=vmin.view(B,1,1), max=vmax.view(B,1,1))
139 x_normalized = (x_clipped - vmin.view(B,1,1)) / (vmax.view(B,1,1) - vmin.view(B,1,1) + 1e-6)
140
141 # generate color map
142 cmap = mpl.cm.get_cmap(cmap_name)
143 colormap = cmap(np.linspace(0, 1, 256))[:,:3] # (256,3)
144 colormap = torch.from_numpy(colormap).float().to(device) # (256,3)
145
146 # vectorized color mapping
147 x_scaled = (x_normalized * 255).long().clamp(0, 255) # (B,H,W)
148 colorized = colormap[x_scaled.flatten()].view(B,H,W,3) # (B,H,W,3)
149
150 # erode the mask
151 if mask is not None:
152 kernel = torch.ones(3,3, device=device)
153 mask_eroded = F.conv2d(
154 mask.float().unsqueeze(1),
155 kernel.view(1,1,3,3),
156 padding=1
157 ) == kernel.numel()

Callers 1

save_depth_mapsFunction · 0.85

Calls 1

get_vertical_colorbarFunction · 0.85

Tested by

no test coverage detected