every blog every motto: Just live your life cause we don’t live twice.
0. 前言
關於圖像位深度,色深的小結
說明:
- 有不對的地方懇請指正,這方面不是太確定。
- 代碼基於jupyter notebook
- 關於dtype 的辨析,可以參考我是dtype辨析
1. 正文
一張圖像包括基本的信息(長,寬,通道)
from PIL import Image
import numpy as np
img = Image.open('ele.jpg')
img
img.size
img_array = np.array(img)
img_array.shape
那什麼又是位深度呢?
1.1 位深度(bit depth)
- 單個像素點(一個通道)上需要用多少比特(bit)來存儲數據,常見的是8位
- 8位,像素點的範圍是0-255(256個值),因此位深度是8
1.2 色深
- 單個像素點(圖片中所有通道)上需要用多少比特(bit)來存儲數據。
- 比如,對於一張RGB的彩色圖像,一個通道上的一個像素點,是8位;對於整張圖像(三個通道)上的一個像素點,色深是24位(3*8),
一句話概括:位深度,每一個像素(僅看一個通道)存儲所需要的位(bit)數;色深,每個像素(整張圖片,或是說所有通道)存儲所需要的位(bit)數;
從某種意義上,二者一樣,只是看到角度不同。
1.3 查看及改變位深度
from PIL import Image
im = Image.open("xiao.png")
print(im.getbands())
輸出:
('R', 'G', 'B')
根據返回的模式(model),依照下表,可知道具體的位深度。
1.4 改變圖像位深度
1.4.1 方法一
先轉成數組,數組轉成圖片時,改變位深度
img = Image.open('16label.png')
img_array = np.array(img)
img.getbands()
根據模式(model) ,可知,圖像屬於32位整型圖像
img_array.dtype
也可以通過將圖片轉換成數組,後查看數組內數據的類型,知道。
轉成成8位圖像
img = Image.fromarray(np.uint8(img_array))
img.getbands()
由返回的模式知道,圖像已轉換位8位圖像。
圖片再轉換成數組,驗證
img_array = np.array(img)
img_array.dtype
1.4.2 方法二
圖片轉成數組時改變位深度,數組再轉成圖片
img2 = Image.open('test2.png')
img2.getbands()
改變數組的數據類型
img_array2 = np.array(img2,dtype='uint8')
img_array2.dtype
img2 = Image.fromarray(img_array2)
img2.getbands()
1.4.3 小結
改變位深度的兩種方法,形象化的理解就是在如下的位置(1 或 2)中改變。
1.5 圖片和數組相互轉換(附)
from PIL import Image
import numpy as np
img = Image.open('ele.jpg')
圖片轉數組
img_array = np.array(img)
查看數據類型
type(img_array)
** 數組轉圖片**
方法一:
img_new = Image.fromarray(np.uint8(img_array))
方法二:
img_new = Image.fromarray(img_array.astype('uint8'))
參考文獻
[1] https://zdaiot.com/Python/%E5%B8%B8%E7%94%A8%E7%AC%AC%E4%B8%89%E6%96%B9%E5%8C%85/PIL%E6%80%BB%E7%BB%93/
[2] https://blog.csdn.net/bigapple88/article/details/5625742?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-4&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-4
[3] https://blog.csdn.net/csdn66_2016/article/details/82850695
[4] https://pillow.readthedocs.io/en/5.2.x/handbook/concepts.html?highlight=getbands
[5] https://blog.csdn.net/weixin_39190382/article/details/104975601