1.将图像转换为一维数组
byteArray = bytearray(image);
2.把一维数组转换为图像
grayImage = numpy.array(grayByteArray).reshape(height, width);
bgrImage = numpy.array(bgrByteArray).reshape(height, width, 3);
3.随机生成的bytearray转换为灰度图像或者BGR图像
import cv2
import numpy
import os
#Make an array of 120,000 random bytes.
randomByteArray = bytearray(os.urandom(120000))
flatNumpyArray = numpy.array(randomByteArray) #转换为NumPy数组
# numpy.random.randint(0, 256, 120000).reshape(300, 400)更简单
#Convert the array to make a 400*300 grayscale image.
grayImage = flatNumpyArray.reshape(300, 400)
cv2.imwrite('RandomGray.png', grayImage)
#Convert the array to make a 400*100 color image.
bgrImage = flatNumpyArray.reshape(100, 400, 3)
cv2.imwrite('RandomColor.png', bgrImage)