10

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!

2 Answers 2

19

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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')

1 Comment

OP asks about OpenCV, why bring in PIL?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.