Python 创建pygame.Color有时会抛出ValueError:颜色参数无效

Python 创建pygame.Color有时会抛出ValueError:颜色参数无效,python,numpy,pygame,Python,Numpy,Pygame,我试图通过从整数元组构造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.C

我试图通过从整数元组构造
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)
虽然可以从
random_values
元组创建
pygame.Color
的第一个实例,但我无法从
numpy_values
元组创建另一个
pygame.Color
实例。然而这两个元组在
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
pygame 1.9.6
大家好,来自pygame社区。https://www.pygame.org/contribute.html
已成功创建pygame。颜色:(143、12、128、61)
像素颜色:(166、166、166、255)
numpy值:(191141191255)
回溯(最近一次呼叫最后一次):
文件“minimal.py”,第24行,在
新像素颜色=pygame.color(*numpy\u值)
ValueError:颜色参数无效

numpy.clip的结果不是一个真正的整数!
numpy\u值
不是整数的元组

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

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

您可以使用
max(min(255,value),0)
intead of
numpy.clip(value,025)
,它将给出整数。很好的建议,这样模块就不会有numpy依赖项。谢谢