matplotlib數組轉圖片的一些坑


最近用matplotlib遇到了一些坑,記錄一下。

圖片轉數組

import matplotlib.pyplot as plt

im_file='test_image.jpg'
img=plt.imread(im_file)
print(img.shape)
print(img.dtype)
# img: numpy array with shape (H,W,c)
# uint8

如上,類型是uint8的。

數組轉圖片

分為以下情況:3通道和單通道,浮點數組和整形數組。

三通道,浮點數組

三通道的shape是(H,W,C)

對於這種情況,不論原數組取值范圍是多少,默認按0-1范圍處理,超出范圍的直接進行clip操作。也就是小於0的數按0(純黑色)處理,大於1的按1(純白)處理。

同時會給出警告:

Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).

如果不加cmap='gray'的話,默認顯示熱度圖。

# float array, 3 channels
# For float array with 3 channels, by default the values out of range [0,1] are **Clipped** !
x=np.ones([500,600,3])
x*=0.4
for i in range(100,200):
    x[i]=np.ones([600,3])*9
for i in range(250,300):
    x[i]=np.ones([600,3])*-2
for i in range(370,400):
    x[i]=np.ones([600,3])*0.7
print(x.dtype)
plt.imshow(x)
plt.axis('off')
plt.show()

暫時不貼圖了,可以自己試一試效果。

結果應該是灰色背景,從上到下依次是白、黑、淺灰三個橫向條帶。

如果數組是真實rgb值,建議先歸一化到0-1,即x=x/255.

單通道,浮點數組

單通道的shape是二維的(H,W),如果是(H,W,1)會報錯。

對於單通道數組,默認進行歸一化,即原數組中最大值被映射到1,最小值被映射到0。

# float array, 1 channel
# For float array with 1 channels, by default all values are normalized
x=np.ones([500,600])
x*=100
for i in range(100,200):
    x[i]=np.ones([600])*200
print(x.dtype)
plt.imshow(x,cmap='gray')
plt.axis('off')
plt.show()

結果是黑色背景白色條帶。

使用plt.imshow(x,cmap='gray', clim=(0,255)),即將0作為黑色,將255作為白色處理。

三通道,整形

默認會對超出0-255的部分進行clip處理。即小於0視為0(黑色),大於255視為255(白色)。

# int array, 3 channels
x=np.ones([500,600,3])
x*=100
for i in range(100,200):
    x[i]=np.ones([600,3])*900
for i in range(250,300):
    x[i]=np.ones([600,3])*-2
for i in range(370,400):
    x[i]=np.ones([600,3])*200
x=x.astype(np.int64)
print(x.dtype)
plt.imshow(x)
plt.axis('off')
plt.show()

單通道,整形

默認情況下,最小值映射到0(黑色),最大值映射到255(白色)。

# int array, 1 channel
# For int array, by default the array range is mapped to [0,255].
x=np.ones([500,600])
x*=100
for i in range(100,200):
    x[i]=np.ones([600])*175
x=x.astype(np.int64)
print(x)
print(x.dtype)
plt.imshow(x,cmap='gray')
plt.axis('off')
plt.show()

同上,如果數組本身是真實灰度值,使用plt.imshow(x,cmap='gray',clim=[0,255])處理。

總結

matplotlib讀取jpg圖片時,默認是uint8類型的numpy數組。

在將numpy數組轉圖片顯示時,浮點形默認處理范圍是0-1,整形默認處理范圍是0-255。

對於三通道數組,超出范圍的進行clip處理,對於單通道數組,默認將數組范圍線性映射到對應類型的處理范圍。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM