Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use GPU for otherwise very slow "Image Film Grain" node (if available) #462

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 15 additions & 13 deletions WAS_Node_Suite.py
Original file line number Diff line number Diff line change
Expand Up @@ -6252,24 +6252,27 @@ def film_grain(self, image, density, intensity, highlights, supersample_factor):
return (pil2tensor(self.apply_film_grain(tensor2pil(image), density, intensity, highlights, supersample_factor)), )

def apply_film_grain(self, img, density=0.1, intensity=1.0, highlights=1.0, supersample_factor=4):
"""
Apply grayscale noise with specified density, intensity, and highlights to a PIL image.
"""

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

#Apply grayscale noise with specified density, intensity, and highlights to a PIL image.
img_gray = img.convert('L')
original_size = img.size
img_gray = img_gray.resize(
((img.size[0] * supersample_factor), (img.size[1] * supersample_factor)), Image.Resampling(2))
num_pixels = int(density * img_gray.size[0] * img_gray.size[1])

noise_pixels = []
for i in range(num_pixels):
x = random.randint(0, img_gray.size[0]-1)
y = random.randint(0, img_gray.size[1]-1)
noise_pixels.append((x, y))

for x, y in noise_pixels:
value = random.randint(0, 255)
img_gray.putpixel((x, y), value)
img_gray_tensor = torch.from_numpy(np.array(img_gray).astype(np.float32) / 255.0).to(device)
img_gray_flat = img_gray_tensor.view(-1)
num_pixels = int(density * img_gray_flat.numel())
indices = torch.randint(0, img_gray_flat.numel(), (num_pixels,), device=img_gray_flat.device)
values = torch.randint(0, 256, (num_pixels,), device=img_gray_flat.device, dtype=torch.float32) / 255.0

img_gray_flat[indices] = values
img_gray = img_gray_flat.view(img_gray_tensor.shape)

img_gray_np = (img_gray.cpu().numpy() * 255).astype(np.uint8)
img_gray = Image.fromarray(img_gray_np)

img_noise = img_gray.convert('RGB')
img_noise = img_noise.filter(ImageFilter.GaussianBlur(radius=0.125))
Expand All @@ -6279,7 +6282,6 @@ def apply_film_grain(self, img, density=0.1, intensity=1.0, highlights=1.0, supe
enhancer = ImageEnhance.Brightness(img_final)
img_highlights = enhancer.enhance(highlights)

# Return the final image
return img_highlights


Expand Down