Reputation: 2942
I am trying to modify the color value of a pixel by constructing a pygame.Color
object from a integer tuple, but for some reason I cannot do what is normally quite possible:
import pygame
import numpy
import random
# it is possible to create a pygame.Color from a tuple of values:
random_values = tuple((random.randint(0, 255) for _ in range(4)))
color = pygame.Color(*random_values)
print(f"successfully created pygame.Color: {color}")
# now for some real application. A certain pixel has this color:
pixel_color = pygame.Color(2795939583) # (166, 166, 166, 0)
print(f"pixel color: {pixel_color}")
# planning to change the intensity of the individual color channels R, G, B, A:
intensity = 25
factors = (1, -1, 1, 0)
# the following will add or subtract 25 from each channel in the pixel_color (while keeping them in range [0,255]):
# pixel_color: (166, 166, 166, 0)
# relative change: (+25, -25, +25, 0)
# resulting color: (191, 141, 191, 0)
numpy_values = tuple(numpy.clip(channel + (intensity * factor), 0, 255) for channel, factor in zip(pixel_color, factors))
print(f"numpy values: {numpy_values}")
new_pixel_color = pygame.Color(*numpy_values)
While the first instance of pygame.Color
can be created from the random_values
tuple, I cannot create another pygame.Color
instance from the numpy_values
tuple. Yet both tuples seem identical in type
and repr
. I get this output:
pygame 1.9.6
Hello from the pygame community. https://www.pygame.org/contribute.html
successfully created pygame.Color: (143, 12, 128, 61)
pixel color: (166, 166, 166, 255)
numpy values: (191, 141, 191, 255)
Traceback (most recent call last):
File "minimal.py", line 24, in <module>
new_pixel_color = pygame.Color(*numpy_values)
ValueError: invalid color argument
Upvotes: 3
Views: 312
Reputation: 2942
The result of the numpy.clip
was not a real integer! the numpy_values
was not a tuple of integers.
After converting the results to int, the problem is solved!
numpy_values = tuple(int(numpy.clip(channel + (intensity * factor), 0, 255)) for channel, factor in zip(pixel_color, factors))
Upvotes: 5