我正在使用 OpenCV 和 Python 实现一张图片,要求是为图像中的每个像素分配随机的 R、G、B 颜色。
这是我当前的代码:
red, green, blue = (255, 0, 0), (0, 255, 0), (0, 0, 255)
rgb = [red, green, blue]
image = img_gen(width, height, rgb_color = random.choice(rgb))
width, height = 640, 480
def img_gen(width, height, rgb_color=(0, 0, 0)):
...
for x in range (0, width):
for y in range (0, height):
# what code should be inserted here?
我现在可以通过仅分配一个随机选择来填充整个图像来实现一张图片,但我想知道如何访问每个“像素”。
最佳答案
使用 numpy,可以轻松创建具有随机颜色像素的图像。为了与 OpenCV 一起使用,您通常希望数据类型为 uint8(0 到 255 之间的整数):
import numpy as np
width, height = 640, 480
img = np.round(np.random.rand(height, width, 3) * 255).astype(np.uint8)
print(img.shape) # (480, 640, 3)
print(img.dtype) # uint8
请注意,numpy 在宽度之前使用高度:)
关于python - 将 RGB 中的随机颜色分配到图像中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26813703/