Color averaging for trees being generated in final step, to make them blend better with actual forest color

This commit is contained in:
Marcus Str. 2024-12-20 19:30:02 +01:00
parent eb68996385
commit 5f214308c4

View File

@ -252,7 +252,7 @@ class mstr_photogen:
# Generates some random tree.
# We will now move away from using pre-made trees...
# they didn't look so great
def generate_tree(self):
def generate_tree(self, bccolor=[(0,0,0)]):
sx = randrange(18, 31)
sy = randrange(18, 31)
@ -270,34 +270,38 @@ class mstr_photogen:
# How many of those have been drawn?
ptsdrawn = 0
bc = [
(36, 50, 52),
(30, 41, 39),
(32, 45, 37),
(32, 39, 49),
(33, 34, 40),
(44, 50, 53),
(40, 46, 48),
(14, 31, 38),
(17, 41, 33),
(39, 56, 35),
(51, 51, 42),
(12, 27, 31),
(45, 59, 48),
(37, 54, 29),
(59, 50, 34),
(59, 59, 35),
(59, 51, 35),
(70, 72, 45),
(48, 59, 44),
(29, 47, 23),
(47, 61, 43),
(29, 68, 15),
(53, 77, 63),
(20, 68, 40)
]
bcp = randrange(0, len(bc))
bc = []
bcp = 0
if bccolor[0] == 0:
bc = [
(36, 50, 52),
(30, 41, 39),
(32, 45, 37),
(32, 39, 49),
(33, 34, 40),
(44, 50, 53),
(40, 46, 48),
(14, 31, 38),
(17, 41, 33),
(39, 56, 35),
(51, 51, 42),
(12, 27, 31),
(45, 59, 48),
(37, 54, 29),
(59, 50, 34),
(59, 59, 35),
(59, 51, 35),
(70, 72, 45),
(48, 59, 44),
(29, 47, 23),
(47, 61, 43),
(29, 68, 15),
(53, 77, 63),
(20, 68, 40)
]
bcp = randrange(0, len(bc))
else:
bc = bccolor
treedraw = ImageDraw.Draw(tree)
while ptsdrawn < treepts + 1:
@ -347,6 +351,37 @@ class mstr_photogen:
# Preload the water layer for comparison
wtrpix = wtrlyr.load()
# To make trees blend better with the environment, we can determine
# an average color from the forest layer. The pass this color as
# base instead.
forest = -1
curlyr = 0
for lyr in self._lyrnames:
if lyr[0] == "landuse" and lyr[1] == "forest":
forest = curlyr
# Find the average color of the forest layer
frstavg = [0,0,0]
frstpix = None
if forest != -1:
numusedpix = 0
frstpix = layers[forest].load()
avg=[0,0,0]
for y in range(0, self._imgsize):
for x in range(0, self._imgsize):
frs = frstpix[x,y]
if frs[3] > 0:
avg[0] = avg[0] + frs[0]
avg[1] = avg[1] + frs[1]
avg[2] = avg[2] + frs[2]
numusedpix = numusedpix + 1
# Calculate and set average
frstavg[0] = int(avg[0] / numusedpix)
frstavg[1] = int(avg[1] / numusedpix)
frstavg[2] = int(avg[2] / numusedpix)
# Walk through list of layers to decide where to add the trees
curlyr = 0
for lyr in self._lyrnames:
@ -363,11 +398,9 @@ class mstr_photogen:
lp = lyrmask[lx,ly]
wp = wtrpix[lx,ly]
if lp[3] == 255 and wp[3] == 0: # Exclude water bodies from tree placement
tree = self.generate_tree()
tree = self.generate_tree(bccolor=[(frstavg[0], frstavg[1], frstavg[2])])
trees.alpha_composite(tree, (lx, ly))
trees = ImageEnhance.Contrast(trees).enhance(0.8)
tree_shadow = Image.new("RGBA", (self._imgsize, self._imgsize))
tree_pix = trees.load()
shadow_pix = tree_shadow.load()