superasperatus
superasperatus

Reputation: 113

Creating an RGB picture in Python with OpenCV from a randomized array

I want to create a RGB image made from a random array of pixel values in Python with OpenCV/Numpy setup.

I'm able to create a Gray image - which looks amazingly live; with this code:

import numpy as np
import cv2

pic_array=np.random.randint(255, size=(900,800))
pic_array_8bit=slika_array.astype(np.uint8)
pic_g=cv2.imwrite("pic-from-random-array.png", pic_array_8bit)

But I want to make it in color as well. I've tried converting with cv2.cvtColor() but it couldnt work.

The issue might be in an array definition or a missed step. Couldn't find a similar situation... Any help how to make a random RGB image in color, would be great.

thanks!

Upvotes: 10

Views: 12382

Answers (2)

user8190410
user8190410

Reputation: 1314

RGB image is composed of three grayscale images. You can make three grayscale images like

rgb = np.random.randint(255, size=(900,800,3),dtype=np.uint8)
cv2.imshow('RGB',rgb)
cv2.waitKey(0)

Upvotes: 19

ravi
ravi

Reputation: 6328

First, you should define a random image data consisting of 3 channels using numpy as shown below-

import numpy as np
data = np.random.randint(0, 255, size=(900, 800, 3), dtype=np.uint8)

Now use, python imaging library as shown below-

from PIL import Image
img = Image.fromarray(data, 'RGB')
img.show()

You can also save the image easily using save function

img.save('image.png')

Upvotes: 0

Related Questions