主要步骤
1.生成普通python数组(bytearray(),os.urandom())
2.转换成numpy数组(numpy.array())
3.通过reshape将数组转换到所需的维数
4.以图像的形式显示出来(cv.imshow())
代码
import os import cv2 as cvimport numpy as np # Make an array of 120000 random bytesrandomByteArray = bytearray(os.urandom(120000))# translate into numpy arrayflatNumpyArray = np.array(randomByteArray)# Convert the array to make a 400*300 grayscale image(灰度图像)grayImage = flatNumpyArray.reshape(300, 400)# show gray imagecv.imshow('GrayImage', grayImage)# print image's arrayprint(grayImage)cv.waitKey() # byte array translate into RGB imagerandomByteArray1 = bytearray(os.urandom(360000))flatNumpyArray1 = np.array(randomByteArray1)BGRimage = flatNumpyArray1.reshape(300,400,3)cv.imshow('BGRimage', BGRimage)cv.waitKey()cv.destroyAllWindows()效果
以上这篇python-OpenCV 实现将数组转换成灰度图和彩图就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。