import cv2
import numpy as np
import os
randomByteArray = bytearray(os.urandom(120000))
flatNumpyArray = np.array(randomByteArray)
grayImage = flatNumpyArray.reshape(300,400)
cv2.imwrite('RandomGray.png',grayImage)
bgrImage = flatNumpyArray.reshape(100,400,3)
cv2.imwrite('RandomColor.png',bgrImage)
os.urandom是通过系统函数获取的随机数
reshape(300, 400) 产生灰度图
flatNumpyArray.reshape(100, 400, 3)比上面多了一个参数,3,这个就是RGB数据。
https://github.com/kingroc711/OpenCVSample/blob/master/OpenCV/3-RandomImage.py