我试图通过从整数元组构造一个pygame.Color
对象来修改像素的颜色值,但是由于某些原因,我无法完成通常可能的事情:
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)
虽然可以从pygame.Color
元组创建random_values
的第一个实例,但是我不能从pygame.Color
元组创建另一个numpy_values
实例。然而,两个元组在type
和repr
中似乎是相同的。我得到以下输出:
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
答案 0 :(得分:5)
In [1]: c = ConcreteC('foobar')
In [2]: c.a
Out[2]: 'foobar'
In [3]: c.a = 'poney'
In [4]: c.a
Out[4]: 'poney'
的结果不是一个整数! numpy.clip
不是整数元组。
将结果转换为int后,问题就解决了!
numpy_values