生成灰度圖像並colormap

編程實現二進制數據的讀寫

代碼

import struct
import numpy as np
a = np.arange(512*512, dtype=np.int32).reshape((512,512))#np.int32 表示整數;reshape爲二維數組
for i in range(512):
    for j in range(512):     #對角漸變圖
        a[i][j]=(i+j)/4
with open('graydraw.dat','wb') as f:
    for row in range(512):
        for col in range(512):
            sn=struct.pack('i',a[row][col]) #序列化
            f.write(sn)

b = np.zeros((512,512), dtype=np.int32)#空數組存數據
with open('graydraw.dat','rb') as f:
    for row in range(512):
        for col in range(512):
            sn=f.read(4)
            b[row][col],=struct.unpack('i',sn)  #使用指定格式反序列化
print(b)

自己生成一幅圖像,顯示(通過第三方軟件顯示,驗證對錯)

在上述代碼中,將寫入文件中.dat換爲.raw,在imageJ中顯示,即可獲得圖像。

代碼

import struct
import numpy as np
#設置數據類型
a = np.arange(512*512, dtype=np.int32).reshape((512,512))#np.int32 表示整數;reshape爲二維數組
for i in range(512):
    for j in range(512):     #對角漸變圖
        a[i][j]=(i+j)/4
with open('drawgray.raw','wb') as f:
    for row in range(512):
        for col in range(512):
            sn=struct.pack('i',a[row][col]) 
            f.write(sn)

使用ImageJ觀察結果

從下面圖片中我們可以看到,灰度值在慢慢變大,由0增大到255,這符合我們設定的函數值。
在這裏插入圖片描述

改變“傳輸函數”,將圖像變爲“彩色”,並進一步瞭解其工作原理

使用cmap作爲傳輸函數

代碼

import struct
import numpy as np
import matplotlib.pyplot as plt
#先生成一維數組,然後再reshape爲2維數組
a = np.arange(512*512, dtype=np.int32).reshape((512,512))#np.int32 表示整數;reshape爲二維數組
for i in range(512):
    for j in range(512):     #對角漸變圖
        a[i][j]=(i+j)/4
#x = np.random.rand(100,100)* 255 #隨機產生一個值,賦值給像素灰度值
#plt.imshow(a,cmap='gray')
plt.imshow(a,cmap ='spring',interpolation ='nearest',vmin = 0,vmax = 255)
#關閉座標軸顯示,並且去掉旁邊空白;參考:https://blog.csdn.net/jifaley/article/details/79687000
plt.axis('off')
fig = plt.gcf()
fig.set_size_inches(7.0/3,7.0/3) #dpi = 300, output = 700*700 pixels
plt.gca().xaxis.set_major_locator(plt.NullLocator())
plt.gca().yaxis.set_major_locator(plt.NullLocator())
plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, hspace = 0, wspace = 0)
plt.margins(0,0)
fig.savefig('text.png', transparent=True, dpi=300, pad_inches = 0)

plt.show()

其中,cmap可取各種值;取值範圍見:matplotlib colormaps官方解說網站

結果

取值cmap=‘spring’:

隨着灰度值的增加,cmap=spring 時色板如下:
在這裏插入圖片描述
灰度圖cmap映射結果:
在這裏插入圖片描述
這與我們的灰度圖是相對應的,也相當好看。

取值cmap=‘hsv’:

隨着灰度值的增加,cmap=hsv 時色板如下:
在這裏插入圖片描述
灰度圖cmap映射結果:
在這裏插入圖片描述

自制傳輸函數

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章