MCPcopy Create free account
hub / github.com/YesianRohn/TextSSR / preprocess_mask

Function preprocess_mask

diffusers/examples/community/lpw_stable_diffusion.py:416–444  ·  view source on GitHub ↗
(mask, batch_size, scale_factor=8)

Source from the content-addressed store, hash-verified

414
415
416def preprocess_mask(mask, batch_size, scale_factor=8):
417 if not isinstance(mask, torch.Tensor):
418 mask = mask.convert("L")
419 w, h = mask.size
420 w, h = (x - x % 8 for x in (w, h)) # resize to integer multiple of 8
421 mask = mask.resize((w // scale_factor, h // scale_factor), resample=PIL_INTERPOLATION["nearest"])
422 mask = np.array(mask).astype(np.float32) / 255.0
423 mask = np.tile(mask, (4, 1, 1))
424 mask = np.vstack([mask[None]] * batch_size)
425 mask = 1 - mask # repaint white, keep black
426 mask = torch.from_numpy(mask)
427 return mask
428
429 else:
430 valid_mask_channel_sizes = [1, 3]
431 # if mask channel is fourth tensor dimension, permute dimensions to pytorch standard (B, C, H, W)
432 if mask.shape[3] in valid_mask_channel_sizes:
433 mask = mask.permute(0, 3, 1, 2)
434 elif mask.shape[1] not in valid_mask_channel_sizes:
435 raise ValueError(
436 f"Mask channel dimension of size in {valid_mask_channel_sizes} should be second or fourth dimension,"
437 f" but received mask of shape {tuple(mask.shape)}"
438 )
439 # (potentially) reduce mask channel dimension from 3 to 1 for broadcasting to latent shape
440 mask = mask.mean(dim=1, keepdim=True)
441 h, w = mask.shape[-2:]
442 h, w = (x - x % 8 for x in (h, w)) # resize to integer multiple of 8
443 mask = torch.nn.functional.interpolate(mask, (h // scale_factor, w // scale_factor))
444 return mask
445
446
447class StableDiffusionLongPromptWeightingPipeline(

Callers 1

__call__Method · 0.70

Calls 2

resizeMethod · 0.45
interpolateMethod · 0.45

Tested by

no test coverage detected