use numpy for base image creation

This commit is contained in:
Denis Lehmann 2021-11-22 15:03:14 +01:00
parent 138d663cfc
commit 2a25d8561f
2 changed files with 13 additions and 29 deletions

View File

@ -21,6 +21,7 @@
src = self; src = self;
propagatedBuildInputs = with pkgs; [ propagatedBuildInputs = with pkgs; [
python3Packages.colour python3Packages.colour
python3Packages.numpy
python3Packages.pillow python3Packages.pillow
]; ];
}; };
@ -38,6 +39,7 @@
buildInputs = with pkgs; [ buildInputs = with pkgs; [
python3 python3
python3Packages.colour python3Packages.colour
python3Packages.numpy
python3Packages.pillow python3Packages.pillow
python3Packages.pip python3Packages.pip
python3Packages.setuptools python3Packages.setuptools

View File

@ -2,6 +2,7 @@
from PIL import Image, ImageDraw, ImageOps from PIL import Image, ImageDraw, ImageOps
from colour import Color from colour import Color
import numpy as np
import random import random
@ -68,37 +69,18 @@ def create_base_image(c1, c2, c3, c4, width=1920, height=1080):
c3 - bottom right c3 - bottom right
c4 - bottom left c4 - bottom left
""" """
# Lambda for adding four colors r = np.linspace(
add = lambda c1, c2, c3, c4: ( np.linspace(c1[0], c4[0], height), np.linspace(c2[0], c3[0], height), width
c1[0] + c2[0] + c3[0] + c4[0], )
c1[1] + c2[1] + c3[1] + c4[1], g = np.linspace(
c1[2] + c2[2] + c3[2] + c4[2], np.linspace(c1[1], c4[1], height), np.linspace(c2[1], c3[1], height), width
)
b = np.linspace(
np.linspace(c1[2], c4[2], height), np.linspace(c2[2], c3[2], height), width
) )
# Lambda for multiplying a color with a factor im_arr = np.array([r, g, b]).T
mul = lambda c, x: (c[0] * x, c[1] * x, c[2] * x) image = Image.fromarray(np.uint8(im_arr * 255)).convert("RGBA")
# Lambda for scaling a color from [0 , 1] to [0, 255]
cor = lambda c: (int(c[0] * 255), int(c[1] * 255), int(c[2] * 255))
# Lambda for calculating a color at x and y in range [0, 1]
# Color limits are set at creation
col = lambda x, y, c1=c1, c2=c2, c3=c3, c4=c4: cor(
add(
mul(c1, (1.0 - x) * (1.0 - y)),
mul(c2, x * (1.0 - y)),
mul(c3, x * y),
mul(c4, (1.0 - x) * y),
)
)
# Create image
image = Image.new("RGBA", (width, height))
pixels = image.load()
for x in range(0, width):
for y in range(0, height):
pixels[x, y] = col(x / (width - 1), y / (height - 1))
return image return image