简体   繁体   English

将RGB中的随机颜色分配给图像

[英]Assigning random colour from RGB into a image

I am implement a picture using OpenCV with Python, the requirement is to assign random R,G,B colour to every pixel into the image. 我使用带有Python的OpenCV实现图片,要求是将随机R,G,B颜色分配给图像中的每个像素。

Here is my current code: 这是我当前的代码:

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?

I can now implement a picture with assigning only one random choice to fill in the whole image, but I want to know hot to access to every "pixel". 我现在可以通过仅分配一个随机选择来填充整个图像来实现图片,但是我想知道可以访问每个“像素”的热点。

Using numpy, it's easy to create an image with randomly colored pixels. 使用numpy,可以轻松创建具有随机彩色像素的图像。 For use with OpenCV, you often want the data type to be uint8 (integers from 0 to 255): 为了与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

Note that numpy uses height before width :) 注意numpy在宽度之前使用height :)

在此处输入图片说明

I'm not exactly sure what your img_gen function returns, but to get a random entry from rgb you can use 我不确定您的img_gen函数返回什么,但是要从rgb中获取随机条目,您可以使用

be sure to import random try : 确保import random尝试:

img = []
for x in range (0, width):
    for y in range (0, height):
        img.append(rgb[random.randint(0,2)])
return img

It really depends on the image format openCV expects in the functions you want to use. 这实际上取决于openCV在您要使用的功能中期望的图像格式。

edit : 编辑:

if you are using numpy you should use 如果您使用的是numpy,则应使用

img = np.array(width*height)

then refer to the content with 然后用

img[x*width + y] = ....

You can simply use - 您可以简单地使用-

img = np.random.rand(width, height, 3);

This will create random pixel values. 这将创建随机像素值。

CAVEAT - RGB values will be between [0,1] and not [0,255]. CAVEAT-RGB值将介于[0,1]而非[0,255]之间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM