Instructions to use phi-lab-rice/GRADE with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Diffusers
How to use phi-lab-rice/GRADE with Diffusers:
pip install -U diffusers transformers accelerate
import torch from diffusers import DiffusionPipeline # switch to "mps" for apple devices pipe = DiffusionPipeline.from_pretrained("phi-lab-rice/GRADE", dtype=torch.bfloat16, device_map="cuda") prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k" image = pipe(prompt).images[0] - Notebooks
- Google Colab
- Kaggle
File size: 8,935 Bytes
f348660 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 | import numpy as np
from scipy.interpolate import LinearNDInterpolator
from PIL import Image
import matplotlib.pyplot as plt
def load_data_path(root, file_name_txt, data_type):
with open(file_name_txt, 'r') as f:
data_path = f.readlines()
data_path = [root + x.strip() + data_type for x in data_path]
return data_path
def load_data_path_nu(root, name_list, data_type):
data_path = [root + x.strip() + data_type for x in name_list]
return data_path
def read_paths(filepath):
'''
Reads a newline delimited file containing paths
Arg(s):
filepath : str
path to file to be read
Return:
list[str] : list of paths
'''
path_list = []
with open(filepath) as f:
while True:
path = f.readline().rstrip('\n')
# If there was nothing to read
if path == '':
break
path_list.append(path)
return path_list
def write_paths(filepath, paths):
'''
Stores line delimited paths into file
Arg(s):
filepath : str
path to file to save paths
paths : list[str]
paths to write into file
'''
with open(filepath, 'w') as o:
for idx in range(len(paths)):
o.write(paths[idx] + '\n')
def load_image(path, normalize=False, data_format='HWC'):
'''
Loads an RGB image
Arg(s):
path : str
path to RGB image
normalize : bool
if set, then normalize image between [0, 1]
data_format : str
'CHW', or 'HWC'
Returns:
numpy[float32] : H x W x C or C x H x W image
'''
# Load image
image = Image.open(path).convert('RGB')
# Convert to numpy
image = np.asarray(image, np.float32)
if data_format == 'HWC':
pass
elif data_format == 'CHW':
image = np.transpose(image, (2, 0, 1))
else:
raise ValueError('Unsupported data format: {}'.format(data_format))
# Normalize
image = image / 255.0 if normalize else image #255.0
return image
def load_depth(path, multiplier=256.0, data_format='HW'):
'''
Loads a depth map from a 16-bit PNG file
Arg(s):
path : str
path to 16-bit PNG file
multiplier : float
multiplier for encoding float as 16/32 bit unsigned integer
data_format : str
HW, CHW, HWC
Returns:
numpy[float32] : depth map
'''
# Loads depth map from 16-bit PNG file
z = np.array(Image.open(path), dtype=np.float32)
# Assert 16-bit (not 8-bit) depth map
z = z / multiplier
z[z <= 0] = 0.0
if data_format == 'HW':
pass
elif data_format == 'CHW':
z = np.expand_dims(z, axis=0)
elif data_format == 'HWC':
z = np.expand_dims(z, axis=-1)
else:
raise ValueError('Unsupported data format: {}'.format(data_format))
return z
def save_depth(z, path, multiplier=256.0):
'''
Saves a depth map to a 16-bit PNG file
Arg(s):
z : numpy[float32]
depth map
path : str
path to store depth map
multiplier : float
multiplier for encoding float as 16/32 bit unsigned integer
'''
z = np.uint32(z * multiplier)
z = Image.fromarray(z, mode='I')
z.save(path)
def save_color_depth(z, path):
'''
Saves a color depth map to a 16-bit PNG file
Arg(s):
z : numpy[float32]
depth map
path : str
path to store depth map
multiplier : float
multiplier for encoding float as 16/32 bit unsigned integer
'''
# Normalize depth map to the range [0, 1]
z_normalized = (z - np.min(z)) / (np.max(z) - np.min(z))
# Convert depth map to color
# colormap = plt.cm.jet # Choose a colormap (e.g., jet)
colormap = plt.cm.viridis
z_color = colormap(z_normalized)
# Scale color values to the range [0, 255] and convert to uint8
z_color = np.uint8(z_color * 255)
# Save color depth map as an image
image = Image.fromarray(z_color)
image.save(path)
def load_response(path, multiplier=2**14, data_format='HW'):
'''
Loads a response map from a 16-bit PNG file
Arg(s):
path : str
path to 16-bit PNG file
multiplier : float
multiplier for encoding float as 16/32 bit unsigned integer
data_format : str
HW, CHW, HWC
Returns:
numpy[float32] : response map
'''
# Loads response map from 16-bit PNG file
response = np.array(Image.open(path), dtype=np.float32)
# Convert using encodering multiplier
response = response / multiplier
if data_format == 'HW':
pass
elif data_format == 'CHW':
response = np.expand_dims(response, axis=0)
elif data_format == 'HWC':
response = np.expand_dims(response, axis=-1)
else:
raise ValueError('Unsupported data format: {}'.format(data_format))
return response
def save_response(response, path, multiplier=2**14):
'''
Saves a response map to a 16-bit PNG file
Arg(s):
response : numpy[float32]
depth map
path : str
path to store depth map
multiplier : float
multiplier for encoding float as 16/32 bit unsigned integer
'''
response = np.uint32(response * multiplier)
response = Image.fromarray(response, mode='I')
response.save(path)
def interpolate_depth(depth_map, validity_map, log_space=False):
'''
Interpolate sparse depth with barycentric coordinates
Arg(s):
depth_map : np.float32
H x W depth map
validity_map : np.float32
H x W depth map
log_space : bool
if set then produce in log space
Returns:
np.float32 : H x W interpolated depth map
'''
assert depth_map.ndim == 2 and validity_map.ndim == 2
rows, cols = depth_map.shape
data_row_idx, data_col_idx = np.where(validity_map)
depth_values = depth_map[data_row_idx, data_col_idx]
# Perform linear interpolation in log space
if log_space:
depth_values = np.log(depth_values)
interpolator = LinearNDInterpolator(
# points=Delaunay(np.stack([data_row_idx, data_col_idx], axis=1).astype(np.float32)),
points=np.stack([data_row_idx, data_col_idx], axis=1),
values=depth_values,
fill_value=0 if not log_space else np.log(1e-3))
query_row_idx, query_col_idx = np.meshgrid(
np.arange(rows), np.arange(cols), indexing='ij')
query_coord = np.stack(
[query_row_idx.ravel(), query_col_idx.ravel()], axis=1)
Z = interpolator(query_coord).reshape([rows, cols])
if log_space:
Z = np.exp(Z)
Z[Z < 1e-1] = 0.0
return Z
def interpolate_depth_ZJU(depth_map, validity_map=None, log_space=False, window_size=12):
'''
Interpolate sparse depth with barycentric coordinates
Args:
depth_map : np.float32
H x W depth map
validity_map : np.float32
H x W depth map
log_space : bool
if set then produce in log space
window_size : int
size of the window for checking validity
Returns:
np.float32 : H x W interpolated depth map
'''
assert depth_map.ndim == 2
if validity_map is None:
validity_map = depth_map > 0.0
rows, cols = depth_map.shape
data_row_idx, data_col_idx = np.where(validity_map)
depth_values = depth_map[data_row_idx, data_col_idx]
# Perform linear interpolation in log space
if log_space:
depth_values = np.log(depth_values)
interpolator = LinearNDInterpolator(
points=np.stack([data_row_idx, data_col_idx], axis=1),
values=depth_values,
fill_value=0 if not log_space else np.log(1e-3))
query_row_idx, query_col_idx = np.meshgrid(np.arange(rows), np.arange(cols), indexing='ij')
Z = np.zeros_like(depth_map)
# Create window indices for each query point
query_indices = np.stack([query_row_idx.ravel(), query_col_idx.ravel()], axis=1)
window_indices = np.indices((window_size, window_size)).reshape(2, -1) - window_size // 2
# Calculate window indices for each query point
window_row_indices = np.clip(query_indices[:, 0, None] + window_indices[0], 0, rows - 1)
window_col_indices = np.clip(query_indices[:, 1, None] + window_indices[1], 0, cols - 1)
# Get window values and check validity
window_values = depth_map[window_row_indices, window_col_indices]
valid_indices = np.any(window_values > 0, axis=1)
# Interpolate for valid query points
valid_query_indices = np.where(valid_indices)[0]
valid_query_coords = query_indices[valid_query_indices]
Z.ravel()[valid_query_indices] = interpolator(valid_query_coords)
if log_space:
Z = np.exp(Z)
Z[Z < 1e-1] = 0.0
return Z |