一、數(shù)字圖像類型以及轉(zhuǎn)換
在skimage中绎巨,一張圖片就是一個簡單的numpy數(shù)組近尚,數(shù)組的數(shù)據(jù)類型有很多種,相互之間也可以轉(zhuǎn)換场勤。這些數(shù)據(jù)類型及取值范圍如下表所示:
Data Type | Range |
---|---|
unit8 | 0 - 255 |
unit16 | 0 - 65535 |
unit32 | 0 - 2^32 |
float | -1 - 1 or 0 - 1 |
int8 | -128 to 127 |
int16 | -32768 to 32767 |
int32 | -2^32 - 2^32-1 |
一張圖片的像素范圍是[0, 255]肿男,所以類型是unit8
,可以通過以下代碼查看圖像的數(shù)據(jù)類型:
from skimage import io, data
img = data.chelsea()
print(img.dtype.name)
輸出為unit8
却嗡。
關(guān)于上表舶沛,需要注意的是float
類型,它的范圍是[0, 1] 或者[-1, 1]窗价。一張彩色圖轉(zhuǎn)換成灰度圖之后就有unit8
變成了float
了如庭。
1、unit8轉(zhuǎn)換成float
from skimage import io, data, img_as_float
img = data.chelsea()
print(img.dtype.name)
img_grey = cimg_as_float(img)
print(img_grey.dtype.name)
輸出為:
uint8 float64
2撼港、float轉(zhuǎn)換成unit8
from skimage import img_as_ubyte
import numpy as np
img = np.array([[0.2], [0.5], [0.1]], dtype=float)
print(img.dtype.name)
img_unit8 = img_as_ubyte(img)
print(img_unit8.dtype.name)
輸出為:
float64 uint8
float轉(zhuǎn)為unit8坪它,有可能會造成數(shù)據(jù)的損失,因此會有警告提醒帝牡。
除了這兩種最常用的轉(zhuǎn)換以外往毡,其實有一些其它的類型轉(zhuǎn)換,如下表:
函數(shù)名 | 功能 |
---|---|
img_as_float | Convert to 64-bit floating point. |
img_as_ubyte | Convert to 8-bit uint. |
img_as_uint | Convert to 16-bit uint. |
img_as_int | Convert to 16-bit int. |
二靶溜、顏色空間及其轉(zhuǎn)換
要想改變圖像的數(shù)據(jù)類型开瞭,除了前文直接改變數(shù)據(jù)類型,我們還可以通過轉(zhuǎn)換顏色空間來實現(xiàn)罩息。
常用的顏色空間有灰度空間嗤详、RGB空間、HSV空間和CMKY空間瓷炮,顏色空間轉(zhuǎn)換以后葱色,數(shù)據(jù)類型都變成了float類型,所有的顏色空間轉(zhuǎn)換函數(shù)都在skimage的color模塊中娘香。
例一:RGB圖轉(zhuǎn)換成灰度圖
from skimage import io, data, color
image = data.chelsea()
image_grey = color.rgb2gray(image)
io.imshow(image_grey)
io.show()
輸出:
print(image.dtype.name, image_grey.dtype.name)
('uint8', 'float64')
其它的轉(zhuǎn)換苍狰,用法都是一樣的,列舉常用的如下:
skimage.color.rgb2grey(rgb) skimage.color.rgb2hsv(rgb) skimage.color.rgb2lab(rgb) skimage.color.gray2rgb(image) skimage.color.hsv2rgb(hsv) skimage.color.lab2rgb(lab)
其實上面函數(shù)的功能都可以通過一個函數(shù)來代替:
skimage.color.convert_colorspace(arr, fromspace, tospace)
表示將arr從fromspace顏色空間轉(zhuǎn)換到tospace顏色空間烘绽。
比如我們可以用其實現(xiàn)小貓圖像由RGB到HSV的轉(zhuǎn)換:
from skimage import io, data, color
image = data.chelsea()
image_hsv = color.convert_colorspace(image, 'RGB', 'HSV')
io.imshow(image_hsv)
io.show()
輸出我就不貼了淋昭,圖片太嚇人。诀姚。
在color模塊中還有一個特別有用的函數(shù):
skimage.color.label2rgb(arr)
响牛,可以根據(jù)標簽值對圖片進行著色。
例二赫段、將小貓圖片分三類并著色
from skimage import io, data, color
import numpy as np
image = data.chelsea()
image_grey = color.rgb2gray(image)
rows, cols = image_grey.shape
labels = np.zeros([rows, cols])
for i in range(rows):
for j in range(cols):
if image_grey[i, j] >0.66:
labels[i, j] = 0
elif image_grey[i, j] > 0.33:
labels[i, j] = 1
else:
labels[i, j] = 2
label_image = color.label2rgb(labels)
io.imshow(label_image)
io.show()
輸出為: