create pygame.Color有时会引发ValueError:无效的color参数

Zab*_*aba 3 python pygame numpy

我正在尝试通过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)
Run Code Online (Sandbox Code Playgroud)

虽然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
Run Code Online (Sandbox Code Playgroud)

Zab*_*aba 5

的结果numpy.clip不是一个真正的整数!该numpy_values不是整数的元组。

将结果转换为int后,问题就解决了!

numpy_values = tuple(int(numpy.clip(channel + (intensity * factor), 0, 255)) for channel, factor in zip(pixel_color, factors))
Run Code Online (Sandbox Code Playgroud)