python - 将 RGB 中的随机颜色分配到图像中

标签 python opencv image-processing

我正在使用 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 在宽度之前使用高度:)

enter image description here

关于python - 将 RGB 中的随机颜色分配到图像中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26813703/

相关文章:

Python ipyleaflet 将 map 导出为 PNG 或 JPG 或 SVG

python-3.x - 使用 Python OpenCV 和 GStreamer 从 UDP 接收器读取 RTSP 流

c++ - 光照不变图像

opencv - 训练级联分类器来检测论文

opencv - 使用 OpenCV 检测写在白板上的符号

python - PyTorch 相当于 tf.dynamic_partition

python - 数据获取检查PUB/SUB模式

python - 如何运行 ParlAI Blender 聊天机器人?

python - ConvexHull 检测矩形(四边形)

python - openCV中的旋转矩阵