主要步驟
1.生成普通python數組(bytearray(),os.urandom())
2.轉換成numpy數組(numpy.array())
3.通過reshape將數組轉換到所需的維數
4.以圖像的形式顯示出來(cv.imshow())
代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
import os import cv2 as cv import numpy as np # Make an array of 120000 random bytes randomByteArray = bytearray(os.urandom( 120000 )) # translate into numpy array flatNumpyArray = np.array(randomByteArray) # Convert the array to make a 400*300 grayscale image(灰度圖像) grayImage = flatNumpyArray.reshape( 300 , 400 ) # show gray image cv.imshow( 'GrayImage' , grayImage) # print image's array print (grayImage) cv.waitKey() # byte array translate into RGB image randomByteArray1 = bytearray(os.urandom( 360000 )) flatNumpyArray1 = np.array(randomByteArray1) BGRimage = flatNumpyArray1.reshape( 300 , 400 , 3 ) cv.imshow( 'BGRimage' , BGRimage) cv.waitKey() cv.destroyAllWindows() |
效果
以上這篇python-OpenCV 實現將數組轉換成灰度圖和彩圖就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/li_l_il/article/details/83214114