欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python?skimage圖像處理

 更新時(shí)間:2022年06月28日 14:42:18   作者:jiandanjinxin  
這篇文章主要為大家介紹了python?skimage圖像處理,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

引言

基于python腳本語(yǔ)言開發(fā)的數(shù)字圖片處理包,比如PIL,Pillow, opencv, scikit-image等。
PIL和Pillow只提供最基礎(chǔ)的數(shù)字圖像處理,功能有限;

opencv實(shí)際上是一個(gè)c++庫(kù),只是提供了python接口,更新速度非常慢。scikit-image是基于scipy的一款圖像處理包,它將圖片作為numpy數(shù)組進(jìn)行處理,正好與matlab一樣,因此,我們最終選擇scikit-image進(jìn)行數(shù)字圖像處理。

scikit-image進(jìn)行數(shù)字圖像處理

Image讀出來(lái)的是PIL的類型,而skimage.io讀出來(lái)的數(shù)據(jù)是numpy格式的

import Image as img
import os
from matplotlib import pyplot as plot
from skimage import io,transform
#Image和skimage讀圖片
img_file1 = img.open('./CXR_png/MCUCXR_0042_0.png')
img_file2 = io.imread('./CXR_png/MCUCXR_0042_0.png')

輸出可以看出Img讀圖片的大小是圖片的(width, height);而skimage的是(height,width, channel), [這也是為什么caffe在單獨(dú)測(cè)試時(shí)要要在代碼中設(shè)置:transformer.set_transpose('data',(2,0,1)),因?yàn)閏affe可以處理的圖片的數(shù)據(jù)格式是(channel,height,width),所以要轉(zhuǎn)換數(shù)據(jù)]

#讀圖片后數(shù)據(jù)的大?。?
print "the picture's size: ", img_file1.size
print "the picture's shape: ", img_file2.shape
the picture's size:  (4892, 4020)
the picture's shape:  (4020, 4892)
#得到像素:
print(img_file1.getpixel((500,1000)), img_file2[500][1000])
print(img_file1.getpixel((500,1000)), img_file2[1000][500])
print(img_file1.getpixel((1000,500)), img_file2[500][1000])

(0, 139)
(0, 0)
(139, 139)

Img讀出來(lái)的圖片獲得某點(diǎn)像素用getpixel((w,h))可以直接返回這個(gè)點(diǎn)三個(gè)通道的像素值
skimage讀出來(lái)的圖片可以直接img_file2[0][0]獲得,但是一定記住它的格式,并不是你想的(channel,height,width)

圖片信息

如果我們想知道一些skimage圖片信息

from skimage import io, data
img = data.chelsea()
io.imshow(img)
print(type(img))  #顯示類型
print(img.shape)  #顯示尺寸
print(img.shape[0])  #圖片高度
print(img.shape[1])  #圖片寬度
print(img.shape[2])  #圖片通道數(shù)
print(img.size)   #顯示總像素個(gè)數(shù)
print(img.max())  #最大像素值
print(img.min())  #最小像素值
print(img.mean()) #像素平均值
print(img[0][0])#圖像的像素值

PIL image 查看圖片信息,可用如下的方法

print type(img)
print img.size  #圖片的尺寸
print img.mode  #圖片的模式
print img.format  #圖片的格式
print(img.getpixel((0,0)))#得到像素:
#img讀出來(lái)的圖片獲得某點(diǎn)像素用getpixel((w,h))可以直接返回這個(gè)點(diǎn)三個(gè)通道的像素值
# 獲取圖像的灰度值范圍
width = img.size[0]
height = img.size[1]
# 輸出圖片的像素值
count = 0 
for i in range(0, width):
    for j in range(0, height):
        if img.getpixel((i, j))>=0 and img.getpixel((i, j))<=255:
            count +=1
print count
print(height*width)

skimage提供了io模塊,顧名思義,這個(gè)模塊是用來(lái)圖片輸入輸出操作的。為了方便練習(xí),也提供一個(gè)data模塊,里面嵌套了一些示例圖片,我們可以直接使用。

skimage包的子模塊

skimage包的全稱是scikit-image SciKit (toolkit for SciPy) ,它對(duì)scipy.ndimage進(jìn)行了擴(kuò)展,提供了更多的圖片處理功能。它是由python語(yǔ)言編寫的,由scipy 社區(qū)開發(fā)和維護(hù)。skimage包由許多的子模塊組成,各個(gè)子模塊提供不同的功能。主要子模塊列表如下:

子模塊名稱                 主要實(shí)現(xiàn)功能
io                            讀取、保存和顯示圖片或視頻
data                       提供一些測(cè)試圖片和樣本數(shù)據(jù)
color                           顏色空間變換
filters             圖像增強(qiáng)、邊緣檢測(cè)、排序?yàn)V波器、自動(dòng)閾值等
draw               操作于numpy數(shù)組上的基本圖形繪制,包括線條、矩形、圓和文本等
transform          幾何變換或其它變換,如旋轉(zhuǎn)、拉伸和拉東變換等
morphology          形態(tài)學(xué)操作,如開閉運(yùn)算、骨架提取等
exposure              圖片強(qiáng)度調(diào)整,如亮度調(diào)整、直方圖均衡等
feature                        特征檢測(cè)與提取等
measure                  圖像屬性的測(cè)量,如相似性或等高線等
segmentation                          圖像分割
restoration                           圖像恢復(fù)
util                                  通用函數(shù)

從外部讀取圖片并顯示

讀取單張彩色rgb圖片,使用skimage.io.imread(fname)函數(shù),帶一個(gè)參數(shù),表示需要讀取的文件路徑。顯示圖片使用skimage.io.imshow(arr)函數(shù),帶一個(gè)參數(shù),表示需要顯示的arr數(shù)組(讀取的圖片以numpy數(shù)組形式計(jì)算)。

from skimage import io
img=io.imread('d:/dog.jpg')
io.imshow(img)

讀取單張灰度圖片,使用skimage.io.imread(fname,as_grey=True)函數(shù),第一個(gè)參數(shù)為圖片路徑,第二個(gè)參數(shù)為as_grey, bool型值,默認(rèn)為False

from skimage import io
img=io.imread('d:/dog.jpg',as_grey=True)
io.imshow(img)

程序自帶圖片

skimage程序自帶了一些示例圖片,如果我們不想從外部讀取圖片,就可以直接使用這些示例圖片:

astronaut     航員圖片      coffee     一杯咖啡圖片   
lena          lena美女圖片   camera   拿相機(jī)的人圖片   
coins           硬幣圖片     moon    月亮圖片
checkerboard   棋盤圖片       horse   馬圖片   
page   書頁(yè)圖片              chelsea   小貓圖片     
hubble_deep_field    星空?qǐng)D片   text   文字圖片
clock    時(shí)鐘圖片   immunohistochemistry   結(jié)腸圖片     

顯示這些圖片可用如下代碼,不帶任何參數(shù)

from skimage import io, data
img=data.lena()
io.imshow(img)

圖片名對(duì)應(yīng)的就是函數(shù)名,如camera圖片對(duì)應(yīng)的函數(shù)名為camera(). 這些示例圖片存放在skimage的安裝目錄下面,路徑名稱為data_dir,我們可以將這個(gè)路徑打印出來(lái)看看

from skimage import data_dir
print(data_dir)

保存圖片

使用io模塊的imsave(fname,arr)函數(shù)來(lái)實(shí)現(xiàn)。第一個(gè)參數(shù)表示保存的路徑和名稱,第二個(gè)參數(shù)表示需要保存的數(shù)組變量。

from skimage import io,data
img=data.chelsea()
io.imshow(img)
io.imsave('d:/cat.jpg',img)

保存圖片的同時(shí)也起到了轉(zhuǎn)換格式的作用。如果讀取時(shí)圖片格式為jpg圖片,保存為png格式,則將圖片從jpg圖片轉(zhuǎn)換為png圖片并保存。

圖像像素的訪問(wèn)與裁剪

圖片讀入程序中后,是以numpy數(shù)組存在的。因此對(duì)numpy數(shù)組的一切功能,對(duì)圖片也適用。對(duì)數(shù)組元素的訪問(wèn),實(shí)際上就是對(duì)圖片像素點(diǎn)的訪問(wèn)。

彩色圖片訪問(wèn)方式為:img[i,j,c]

i表示圖片的行數(shù),j表示圖片的列數(shù),c表示圖片的通道數(shù)(RGB三通道分別對(duì)應(yīng)0,1,2)。坐標(biāo)是從左上角開始。

灰度圖片訪問(wèn)方式為:gray[i,j]

例1:輸出小貓圖片的G通道中的第20行30列的像素值

from skimage import io,data
img=data.chelsea()
pixel=img[20,30,1]
print(pixel)

例2:顯示紅色單通道圖片

from skimage import io,data
img=data.chelsea()
R=img[:,:,0]
io.imshow(R)

除了對(duì)像素進(jìn)行讀取,也可以修改像素值。

例3:對(duì)小貓圖片隨機(jī)添加椒鹽噪聲

from skimage import io,data
import numpy as np
img=data.chelsea()
#隨機(jī)生成5000個(gè)椒鹽
rows,cols,dims=img.shape
for i in range(5000):
    x=np.random.randint(0,rows)
    y=np.random.randint(0,cols)
    img[x,y,:]=255
io.imshow(img)

這里用到了numpy包里的random來(lái)生成隨機(jī)數(shù),randint(0,cols)表示隨機(jī)生成一個(gè)整數(shù),范圍在0到cols之間。

用img[x,y,:]=255這句來(lái)對(duì)像素值進(jìn)行修改,將原來(lái)的三通道像素值,變?yōu)?55

通過(guò)對(duì)數(shù)組的裁剪,就可以實(shí)現(xiàn)對(duì)圖片的裁剪。

例4:對(duì)小貓圖片進(jìn)行裁剪

from skimage import io,data
img=data.chelsea()
roi=img[80:180,100:200,:]
io.imshow(roi)

對(duì)多個(gè)像素點(diǎn)進(jìn)行操作,使用數(shù)組切片方式訪問(wèn)。切片方式返回的是以指定間隔下標(biāo)訪問(wèn) 該數(shù)組的像素值。下面是有關(guān)灰度圖像的一些例子:

img[i,:] = im[j,:] # 將第 j 行的數(shù)值賦值給第 i 行
img[:,i] = 100 # 將第 i 列的所有數(shù)值設(shè)為 100
img[:100,:50].sum() # 計(jì)算前 100 行、前 50 列所有數(shù)值的和
img[50:100,50:100] # 50~100 行,50~100 列(不包括第 100 行和第 100 列)
img[i].mean() # 第 i 行所有數(shù)值的平均值
img[:,-1] # 最后一列
img[-2,:] (or im[-2]) # 倒數(shù)第二行

最后我們?cè)倏磧蓚€(gè)對(duì)像素值進(jìn)行訪問(wèn)和改變的例子:

例5:將lena圖片進(jìn)行二值化,像素值大于128的變?yōu)?,否則變?yōu)?

from skimage import io,data,color
img=data.lena()
img_gray=color.rgb2gray(img)
rows,cols=img_gray.shape
for i in range(rows):
    for j in range(cols):
        if (img_gray[i,j]<=0.5):
            img_gray[i,j]=0
        else:
            img_gray[i,j]=1
io.imshow(img_gray)

color模塊的rgb2gray()函數(shù)

使用了color模塊的rgb2gray()函數(shù),將彩色三通道圖片轉(zhuǎn)換成灰度圖。轉(zhuǎn)換結(jié)果為float64類型的數(shù)組,范圍為[0,1]之間。

將彩色三通道圖片轉(zhuǎn)換成灰度圖,最后變成unit8, float轉(zhuǎn)換為unit8是有信息損失的。

img_path = 'data/dpclassifier/newtrain/test/1_0.png'
import Image as img
import os
from matplotlib import pyplot as plot
from skimage import io,transform, img_as_ubyte
img_file1 = img.open(img_path)
img_file1.show()
img_file2 = io.imread(img_path)
io.imshow(img_file2)
print(type(img_file1),img_file1.mode, type(img_file2),img_file2.shape, img_file2.dtype,img_file2.max(),img_file2.min(),img_file2.mean())
img_file22=skimage.color.rgb2gray(img_file2)
print(type(img_file22),img_file22.shape,img_file22.dtype,img_file22.max(),img_file22.min(),img_file22.mean() )
dst=img_as_ubyte(img_file22)
print(type(dst),dst.shape,dst.dtype, dst.max(), dst.min(), dst.mean())

結(jié)果

(<class 'PIL.PngImagePlugin.PngImageFile'>, 'RGB', <type 'numpy.ndarray'>, (420, 512, 3), dtype('uint8'), 255, 0, 130.9983863467262)
(<type 'numpy.ndarray'>, (420, 512), dtype('float64'), 1.0, 0.0, 0.5137191621440242)
(<type 'numpy.ndarray'>, (420, 512), dtype('uint8'), 255, 0, 130.9983863467262)

例6:

from skimage import io,data
img=data.chelsea()
reddish = img[:, :, 0] &gt;170
img[reddish] = [0, 255, 0]
io.imshow(img)

這個(gè)例子先對(duì)R通道的所有像素值進(jìn)行判斷,如果大于170,則將這個(gè)地方的像素值變?yōu)閇0,255,0], 即G通道值為255,R和B通道值為0。

圖像數(shù)據(jù)類型及顏色空間轉(zhuǎn)換

在skimage中,一張圖片就是一個(gè)簡(jiǎn)單的numpy數(shù)組,數(shù)組的數(shù)據(jù)類型有很多種,相互之間也可以轉(zhuǎn)換。這些數(shù)據(jù)類型及取值范圍如下表所示:

Data type   Range
uint8     0 to 255
uint16    0 to 65535
uint32    0 to 232
float    -1 to 1 or 0 to 1
int8      -128 to 127
int16    -32768 to 32767
int32    -231 to 231 - 1

一張圖片的像素值范圍是[0,255], 因此默認(rèn)類型是unit8, 可用如下代碼查看數(shù)據(jù)類型

from skimage import io,data
img=data.chelsea()
print(img.dtype.name)

在上面的表中,特別注意的是float類型,它的范圍是[-1,1]或[0,1]之間。一張彩色圖片轉(zhuǎn)換為灰度圖后,它的類型就由unit8變成了float

1、unit8轉(zhuǎn)float

from skimage import data,img_as_float
img=data.chelsea()
print(img.dtype.name)
dst=img_as_float(img)
print(dst.dtype.name)

2、float轉(zhuǎn)uint8

from skimage import img_as_ubyte
import numpy as np
img = np.array([0, 0.5, 1], dtype=float)
print(img.dtype.name)
dst=img_as_ubyte(img)
print(dst.dtype.name)

float轉(zhuǎn)為unit8,有可能會(huì)造成數(shù)據(jù)的損失,因此會(huì)有警告提醒。*

除了這兩種最常用的轉(zhuǎn)換以外,其實(shí)有一些其它的類型轉(zhuǎn)換,如下表:

Function name   Description
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ù)類型外,還可以通過(guò)圖像的顏色空間轉(zhuǎn)換來(lái)改變數(shù)據(jù)類型。

常用的顏色空間有灰度空間、rgb空間、hsv空間和cmyk空間。顏色空間轉(zhuǎn)換以后,圖片類型都變成了float型。

所有的顏色空間轉(zhuǎn)換函數(shù),都放在skimage的color模塊內(nèi)。

例:rgb轉(zhuǎn)灰度圖

from skimage import io,data,color
img=data.lena()
gray=color.rgb2gray(img)
io.imshow(gray)

其它的轉(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í)際上,上面的所有轉(zhuǎn)換函數(shù),都可以用一個(gè)函數(shù)來(lái)代替

skimage.color.convert_colorspace(arr, fromspace, tospace)

表示將arr從fromspace顏色空間轉(zhuǎn)換到tospace顏色空間。

例:rgb轉(zhuǎn)hsv

from skimage import io,data,color
img=data.lena()
hsv=color.convert_colorspace(img,'RGB','HSV')
io.imshow(hsv)

在color模塊的顏色空間轉(zhuǎn)換函數(shù)中,還有一個(gè)比較有用的函數(shù)是
skimage.color.label2rgb(arr), 可以根據(jù)標(biāo)簽值對(duì)圖片進(jìn)行著色。以后的圖片分類后著色就可以用這個(gè)函數(shù)。

例:將lena圖片分成三類,然后用默認(rèn)顏色對(duì)三類進(jìn)行著色

from skimage import io,data,color
import numpy as np
img=data.lena()
gray=color.rgb2gray(img)
rows,cols=gray.shape
labels=np.zeros([rows,cols])
for i in range(rows):
    for j in range(cols):
        if(gray[i,j]&lt;0.4):
            labels[i,j]=0
        elif(gray[i,j]&lt;0.75):
            labels[i,j]=1
        else:
            labels[i,j]=2
dst=color.label2rgb(labels)
io.imshow(dst)

圖像的繪制

實(shí)際上前面我們就已經(jīng)用到了圖像的繪制,如:

io.imshow(img)  

這一行代碼的實(shí)質(zhì)是利用matplotlib包對(duì)圖片進(jìn)行繪制,繪制成功后,返回一個(gè)matplotlib類型的數(shù)據(jù)。因此,我們也可以這樣寫:

import matplotlib.pyplot as plt
plt.imshow(img)

imshow()函數(shù)格式為:

matplotlib.pyplot.imshow(X, cmap=None)

X: 要繪制的圖像或數(shù)組。

cmap: 顏色圖譜(colormap), 默認(rèn)繪制為RGB(A)顏色空間。

其它可選的顏色圖譜如下列表:

顏色圖譜                          描述
autumn                        紅-橙-黃
bone                          黑-白,x線
cool                          青-洋紅
copper                         黑-銅
flag                           紅-白-藍(lán)-黑
gray                              黑-白
hot                            黑-紅-黃-白
hsv                hsv顏色空間, 紅-黃-綠-青-藍(lán)-洋紅-紅
inferno                     黑-紅-黃
jet                             藍(lán)-青-黃-紅
magma                      黑-紅-白
pink                               黑-粉-白
plasma                       綠-紅-黃
prism                         紅-黃-綠-藍(lán)-紫-...-綠模式
spring                             洋紅-黃
summer                             綠-黃
viridis                             藍(lán)-綠-黃
winter                             藍(lán)-綠

用的比較多的有g(shù)ray,jet等,如:

plt.imshow(image,plt.cm.gray)
plt.imshow(img,cmap=plt.cm.jet)

在窗口上繪制完圖片后,返回一個(gè)AxesImage對(duì)象。要在窗口上顯示這個(gè)對(duì)象,我們可以調(diào)用show()函數(shù)來(lái)進(jìn)行顯示,但進(jìn)行練習(xí)的時(shí)候(ipython環(huán)境中),一般我們可以省略show()函數(shù),也能自動(dòng)顯示出來(lái)。

from skimage import io,data
img=data.astronaut()
dst=io.imshow(img)
print(type(dst))
io.show()

可以看到,類型是'matplotlib.image.AxesImage'。顯示一張圖片,我們通常更愿意這樣寫:

import matplotlib.pyplot as plt
from skimage import io,data
img=data.astronaut()
plt.imshow(img)
plt.show()

matplotlib是一個(gè)專業(yè)繪圖的庫(kù),相當(dāng)于matlab中的plot,可以設(shè)置多個(gè)figure窗口,設(shè)置figure的標(biāo)題,隱藏坐標(biāo)尺,甚至可以使用subplot在一個(gè)figure中顯示多張圖片。一般我們可以這樣導(dǎo)入matplotlib庫(kù):

import matplotlib.pyplot as plt

也就是說(shuō),我們繪圖實(shí)際上用的是matplotlib包的pyplot模塊。

用figure函數(shù)和subplot函數(shù)分別創(chuàng)建主窗口與子圖分開并同時(shí)顯示宇航員圖片的三個(gè)通道

from skimage import data
import matplotlib.pyplot as plt
img=data.astronaut()
plt.figure(num='astronaut',figsize=(8,8))  #創(chuàng)建一個(gè)名為astronaut的窗口,并設(shè)置大小 
plt.subplot(2,2,1)     #將窗口分為兩行兩列四個(gè)子圖,則可顯示四幅圖片
plt.title('origin image')   #第一幅圖片標(biāo)題
plt.imshow(img)      #繪制第一幅圖片
plt.subplot(2,2,2)     #第二個(gè)子圖
plt.title('R channel')   #第二幅圖片標(biāo)題
plt.imshow(img[:,:,0],plt.cm.gray)      #繪制第二幅圖片,且為灰度圖
plt.axis('off')     #不顯示坐標(biāo)尺寸
plt.subplot(2,2,3)     #第三個(gè)子圖
plt.title('G channel')   #第三幅圖片標(biāo)題
plt.imshow(img[:,:,1],plt.cm.gray)      #繪制第三幅圖片,且為灰度圖
plt.axis('off')     #不顯示坐標(biāo)尺寸
plt.subplot(2,2,4)     #第四個(gè)子圖
plt.title('B channel')   #第四幅圖片標(biāo)題
plt.imshow(img[:,:,2],plt.cm.gray)      #繪制第四幅圖片,且為灰度圖
plt.axis('off')     #不顯示坐標(biāo)尺寸
plt.show()   #顯示窗口

在圖片繪制過(guò)程中,我們用matplotlib.pyplot模塊下的figure()函數(shù)來(lái)創(chuàng)建顯示窗口,該函數(shù)的格式為:

matplotlib.pyplot.figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None)

所有參數(shù)都是可選的,都有默認(rèn)值,因此調(diào)用該函數(shù)時(shí)可以不帶任何參數(shù),其中:

num: 整型或字符型都可以。如果設(shè)置為整型,則該整型數(shù)字表示窗口的序號(hào)。如果設(shè)置為字符型,則該字符串表示窗口的名稱。用該參數(shù)來(lái)命名窗口,如果兩個(gè)窗口序號(hào)或名相同,則后一個(gè)窗口會(huì)覆蓋前一個(gè)窗口。

figsize: 設(shè)置窗口大小。是一個(gè)tuple型的整數(shù),如figsize=(8,8)

dpi: 整形數(shù)字,表示窗口的分辨率。

facecolor: 窗口的背景顏色。

edgecolor: 窗口的邊框顏色。

用figure()函數(shù)創(chuàng)建的窗口,只能顯示一幅圖片,如果想要顯示多幅圖片,則需要將這個(gè)窗口再劃分為幾個(gè)子圖,在每個(gè)子圖中顯示不同的圖片。

=我們可以使用subplot()函數(shù)來(lái)劃分子圖,函數(shù)格式為:

matplotlib.pyplot.subplot(nrows, ncols, plot_number)

nrows: 子圖的行數(shù)。

ncols: 子圖的列數(shù)。

plot_number: 當(dāng)前子圖的編號(hào)。

如:

plt.subplot(2,2,1)

則表示將figure窗口劃分成了2行2列共4個(gè)子圖,當(dāng)前為第1個(gè)子圖。我們有時(shí)也可以用這種寫法:

plt.subplot(221)

兩種寫法效果是一樣的。每個(gè)子圖的標(biāo)題可用title()函數(shù)來(lái)設(shè)置,是否使用坐標(biāo)尺可用axis()函數(shù)來(lái)設(shè)置,如:

plt.subplot(221)
plt.title("first subwindow")
plt.axis('off')  

用subplots來(lái)創(chuàng)建顯示窗口與劃分子圖

除了上面那種方法創(chuàng)建顯示窗口和劃分子圖,還有另外一種編寫方法也可以,如下例:

import matplotlib.pyplot as plt
from skimage import data,color
img = data.immunohistochemistry()
hsv = color.rgb2hsv(img)
fig, axes = plt.subplots(2, 2, figsize=(7, 6))
ax0, ax1, ax2, ax3 = axes.ravel()
ax0.imshow(img)
ax0.set_title("Original image")
ax1.imshow(hsv[:, :, 0], cmap=plt.cm.gray)
ax1.set_title("H")
ax2.imshow(hsv[:, :, 1], cmap=plt.cm.gray)
ax2.set_title("S")
ax3.imshow(hsv[:, :, 2], cmap=plt.cm.gray)
ax3.set_title("V")
for ax in axes.ravel():
    ax.axis('off')
fig.tight_layout()  #自動(dòng)調(diào)整subplot間的參數(shù)

直接用subplots()函數(shù)來(lái)創(chuàng)建并劃分窗口。注意,比前面的subplot()函數(shù)多了一個(gè)s,該函數(shù)格式為:

matplotlib.pyplot.subplots(nrows=1, ncols=1)

nrows: 所有子圖行數(shù),默認(rèn)為1。

ncols: 所有子圖列數(shù),默認(rèn)為1。

返回一個(gè)窗口figure, 和一個(gè)tuple型的ax對(duì)象,該對(duì)象包含所有的子圖,可結(jié)合ravel()函數(shù)列出所有子圖,如:

fig, axes = plt.subplots(2, 2, figsize=(7, 6))

ax0, ax1, ax2, ax3 = axes.ravel()

創(chuàng)建了2行2列4個(gè)子圖,分別取名為ax0,ax1,ax2和ax3, 每個(gè)子圖的標(biāo)題用set_title()函數(shù)來(lái)設(shè)置,如:

ax0.imshow(img)

ax0.set_title("Original image")

如果有多個(gè)子圖,我們還可以使用tight_layout()函數(shù)來(lái)調(diào)整顯示的布局,該函數(shù)格式為:

matplotlib.pyplot.tight_layout(pad=1.08, h_pad=None, w_pad=None, rect=None)

所有的參數(shù)都是可選的,調(diào)用該函數(shù)時(shí)可省略所有的參數(shù)。

pad: 主窗口邊緣和子圖邊緣間的間距,默認(rèn)為1.08

h_pad, w_pad: 子圖邊緣之間的間距,默認(rèn)為 pad_inches

rect: 一個(gè)矩形區(qū)域,如果設(shè)置這個(gè)值,則將所有的子圖調(diào)整到這個(gè)矩形區(qū)域內(nèi)。

一般調(diào)用為:

plt.tight_layout()  #自動(dòng)調(diào)整subplot間的參數(shù)

其它方法繪圖并顯示

除了使用matplotlib庫(kù)來(lái)繪制圖片,skimage還有另一個(gè)子模塊viewer,也提供一個(gè)函數(shù)來(lái)顯示圖片。不同的是,它利用Qt工具來(lái)創(chuàng)建一塊畫布,從而在畫布上繪制圖像。

例:

from skimage import data
from skimage.viewer import ImageViewer
img = data.coins()
viewer = ImageViewer(img)
viewer.show()

最后總結(jié)一下,繪制和顯示圖片常用到的函數(shù)有:

函數(shù)名     功能  調(diào)用格式
figure  創(chuàng)建一個(gè)顯示窗口    plt.figure(num=1,figsize=(8,8)
imshow  繪制圖片    plt.imshow(image)
show    顯示窗口    plt.show()
subplot     劃分子圖    plt.subplot(2,2,1)
title   設(shè)置子圖標(biāo)題(與subplot結(jié)合使用)    plt.title('origin image')
axis    是否顯示坐標(biāo)尺     plt.axis('off')
subplots    創(chuàng)建帶有多個(gè)子圖的窗口     fig,axes=plt.subplots(2,2,figsize=(8,8))
ravel   為每個(gè)子圖設(shè)置變量   ax0,ax1,ax2,ax3=axes.ravel()
set_title   設(shè)置子圖標(biāo)題(與axes結(jié)合使用)   ax0.set_title('first window')
tight_layout    自動(dòng)調(diào)整子圖顯示布局  plt.tight_layout()

圖像的批量處理

有些時(shí)候,我們不僅要對(duì)一張圖片進(jìn)行處理,可能還會(huì)對(duì)一批圖片處理。這時(shí)候,我們可以通過(guò)循環(huán)來(lái)執(zhí)行處理,也可以調(diào)用程序自帶的圖片集合來(lái)處理。
圖片集合函數(shù)為:

skimage.io.ImageCollection(load_pattern,load_func=None)

這個(gè)函數(shù)是放在io模塊內(nèi)的,帶兩個(gè)參數(shù),第一個(gè)參數(shù)load_pattern, 表示圖片組的路徑,可以是一個(gè)str字符串。第二個(gè)參數(shù)load_func是一個(gè)回調(diào)函數(shù),我們對(duì)圖片進(jìn)行批量處理就可以通過(guò)這個(gè)回調(diào)函數(shù)實(shí)現(xiàn)?;卣{(diào)函數(shù)默認(rèn)為imread(),即默認(rèn)這個(gè)函數(shù)是批量讀取圖片。
先看一個(gè)例子:

import skimage.io as io
from skimage import data_dir
str=data_dir + '/*.png'
coll = io.ImageCollection(str)
print(len(coll))

顯示結(jié)果為25, 說(shuō)明系統(tǒng)自帶了25張png的示例圖片,這些圖片都讀取了出來(lái),放在圖片集合coll里。如果我們想顯示其中一張圖片,則可以在后加上一行代碼:

io.imshow(coll[10])

顯示為:

如果一個(gè)文件夾里,我們既存放了一些jpg格式的圖片,又存放了一些png格式的圖片,現(xiàn)在想把它們?nèi)孔x取出來(lái),該怎么做呢?

import skimage.io as io
from skimage import data_dir
str='d:/pic/*.jpg:d:/pic/*.png'
coll = io.ImageCollection(str)
print(len(coll))

注意這個(gè)地方'd:/pic/.jpg:d:/pic/.png' ,是兩個(gè)字符串合在一起的,第一個(gè)是'd:/pic/.jpg', 第二個(gè)是'd:/pic/.png' ,合在一起后,中間用冒號(hào)來(lái)隔開,這樣就可以把d:/pic/文件夾下的jpg和png格式的圖片都讀取出來(lái)。如果還想讀取存放在其它地方的圖片,也可以一并加進(jìn)去,只是中間同樣用冒號(hào)來(lái)隔開。

io.ImageCollection()這個(gè)函數(shù)省略第二個(gè)參數(shù),就是批量讀取。如果我們不是想批量讀取,而是其它批量操作,如批量轉(zhuǎn)換為灰度圖,那又該怎么做呢?

那就需要先定義一個(gè)函數(shù),然后將這個(gè)函數(shù)作為第二個(gè)參數(shù),如:

from skimage import data_dir,io,color
def convert_gray(f): 
       rgb=io.imread(f) 
       return color.rgb2gray(rgb) 
str=data_dir+'/*.png'
coll = io.ImageCollection(str,load_func=convert_gray)
io.imshow(coll[10])

這種批量操作對(duì)視頻處理是極其有用的,因?yàn)橐曨l就是一系列的圖片組合

from skimage import data_dir,io,color
class AVILoader: 
        video_file = 'myvideo.avi' 
        def __call__(self, frame): 
                return video_read(self.video_file, frame)
avi_load = AVILoader()
frames = range(0, 1000, 10) # 0, 10, 20, ...ic =io.ImageCollection(frames, load_func=avi_load)

這段代碼的意思,就是將myvideo.avi這個(gè)視頻中每隔10幀的圖片讀取出來(lái),放在圖片集合中。
得到圖片集合以后,我們還可以將這些圖片連接起來(lái),構(gòu)成一個(gè)維度更高的數(shù)組,連接圖片的函數(shù)為:

skimage.io.concatenate_images(ic)

帶一個(gè)參數(shù),就是以上的圖片集合,如:

from skimage import data_dir,io,color
coll = io.ImageCollection('d:/pic/*.jpg')
mat=io.concatenate_images(coll)

使用concatenate_images(ic)函數(shù)的前提是讀取的這些圖片尺寸必須一致,否則會(huì)出錯(cuò)。我們看看圖片連接前后的維度變化:

from skimage import data_dir,io,color
coll = io.ImageCollection('d:/pic/*.jpg')
print(len(coll)) #連接的圖片數(shù)量
print(coll[0].shape) #連接前的圖片尺寸,所有的都一樣
mat=io.concatenate_images(coll)
print(mat.shape) #連接后的數(shù)組尺寸

顯示結(jié)果:

2
(870, 580, 3)
(2, 870, 580, 3)

可以看到,將2個(gè)3維數(shù)組,連接成了一個(gè)4維數(shù)組

如果我們對(duì)圖片進(jìn)行批量操作后,想把操作后的結(jié)果保存起來(lái),也是可以辦到的。

例:把系統(tǒng)自帶的所有png示例圖片,全部轉(zhuǎn)換成256256的jpg格式灰度圖,保存在d:/data/文件夾下*

改變圖片的大小,我們可以使用tranform模塊的resize()函數(shù),后續(xù)會(huì)講到這個(gè)模塊。

from skimage import data_dir,io,transform,color
import numpy as np
def convert_gray(f):
        rgb=io.imread(f) #依次讀取rgb圖片 
        gray=color.rgb2gray(rgb) #將rgb圖片轉(zhuǎn)換成灰度圖 
        dst=transform.resize(gray,(256,256)) #將灰度圖片大小轉(zhuǎn)換為256*256 
        return dst str=data_dir+'/*.png'
coll = io.ImageCollection(str,load_func=convert_gray)
for i in range(len(coll)): 
    io.imsave('d:/data/'+np.str(i)+'.jpg',coll[i]) #循環(huán)保存圖片

結(jié)果:

圖像的形變與縮放

圖像的形變與縮放,使用的是skimage的transform模塊,函數(shù)比較多,功能齊全。

1、改變圖片尺寸resize

函數(shù)格式為:

skimage.transform.resize(image, output_shape)

image: 需要改變尺寸的圖片

output_shape: 新的圖片尺寸

from skimage import transform,data
import matplotlib.pyplot as plt
img = data.camera()
dst=transform.resize(img, (80, 60))
plt.figure('resize')
plt.subplot(121)
plt.title('before resize')
plt.imshow(img,plt.cm.gray)
plt.subplot(122)
plt.title('before resize')
plt.imshow(dst,plt.cm.gray)
plt.show()

將camera圖片由原來(lái)的512x512大小,變成了80x60大小。從下圖中的坐標(biāo)尺,我們能夠看出來(lái):

2、按比例縮放rescale

函數(shù)格式為:

skimage.transform.rescale(image, scale[, ...])

scale參數(shù)可以是單個(gè)float數(shù),表示縮放的倍數(shù),也可以是一個(gè)float型的tuple,如[0.2,0.5],表示將行列數(shù)分開進(jìn)行縮放

from skimage import transform,data
img = data.camera()
print(img.shape) #圖片原始大小 
print(transform.rescale(img, 0.1).shape) #縮小為原來(lái)圖片大小的0.1
print(transform.rescale(img, [0.5,0.25]).shape) #縮小為原來(lái)圖片行數(shù)一半,列數(shù)四分之一
print(transform.rescale(img, 2).shape) #放大為原來(lái)圖片大小的2倍

結(jié)果為:

(512, 512)
(51, 51)
(256, 128)
(1024, 1024)

3、旋轉(zhuǎn) rotate

skimage.transform.rotate(image, angle[, ...],resize=False)

angle參數(shù)是個(gè)float類型數(shù),表示旋轉(zhuǎn)的度數(shù)

resize用于控制在旋轉(zhuǎn)時(shí),是否改變大小 ,默認(rèn)為False

from skimage import transform,data
import matplotlib.pyplot as plt
img = data.camera()
print(img.shape) #圖片原始大小
img1=transform.rotate(img, 60) #旋轉(zhuǎn)90度,不改變大小 
print(img1.shape)
img2=transform.rotate(img, 30,resize=True) #旋轉(zhuǎn)30度,同時(shí)改變大小
print(img2.shape) plt.figure('resize')
plt.subplot(121)plt.title('rotate 60')
plt.imshow(img1,plt.cm.gray)
plt.subplot(122)
plt.title('rotate 30')
plt.imshow(img2,plt.cm.gray)
plt.show()

顯示結(jié)果:

4、圖像金字塔

以多分辨率來(lái)解釋圖像的一種有效但概念簡(jiǎn)單的結(jié)構(gòu)就是圖像金字塔。圖像金字塔最初用于機(jī)器視覺和圖像壓縮,一幅圖像的金字塔是一系列以金字塔形狀排列的分辨率逐步降低的圖像集合。金字塔的底部是待處理圖像的高分辨率表示,而頂部是低分辨率的近似。當(dāng)向金字塔的上層移動(dòng)時(shí),尺寸和分辨率就降低。
在此,我們舉一個(gè)高斯金字塔的應(yīng)用實(shí)例,函數(shù)原型為:

skimage.transform.pyramid_gaussian(image, downscale=2)

downscale控制著金字塔的縮放比例

import numpy as np
import matplotlib.pyplot as plt
from skimage import data,transform
image = data.astronaut() #載入宇航員圖片
rows, cols, dim = image.shape #獲取圖片的行數(shù),列數(shù)和通道數(shù)
pyramid = tuple(transform.pyramid_gaussian(image, downscale=2)) #產(chǎn)生高斯金字塔圖像#共生成了log(512)=9幅金字塔圖像,加上原始圖像共10幅,pyramid[0]-pyramid[1]
composite_image = np.ones((rows, cols + cols / 2, 3), dtype=np.double) #生成背景composite_image[:rows, :cols, :] = pyramid[0] #融合原始圖像
i_row = 0
for p in pyramid[1:]: 
       n_rows, n_cols = p.shape[:2] 
       composite_image[i_row:i_row + n_rows, cols:cols + n_cols] = p #循環(huán)融合9幅金字塔圖像
       i_row += n_rows
plt.imshow(composite_image)
plt.show()

上右圖,就是10張金字塔圖像,下標(biāo)為0的表示原始圖像,后面每層的圖像行和列變?yōu)樯弦粚拥囊话?,直至變?yōu)?

除了高斯金字塔外,還有其它的金字塔,如:

skimage.transform.pyramid_laplacian(image, downscale=2)

對(duì)比度與亮度調(diào)整

圖像亮度與對(duì)比度的調(diào)整,是放在skimage包的exposure模塊里面

1、gamma調(diào)整

原理:I=Ig

對(duì)原圖像的像素,進(jìn)行冪運(yùn)算,得到新的像素值。公式中的g就是gamma值。

如果gamma>1, 新圖像比原圖像暗

如果gamma<1,新圖像比原圖像亮

函數(shù)格式為:

skimage.exposure.adjust_gamma(image, gamma=1)

gamma參數(shù)默認(rèn)為1,原像不發(fā)生變化 。

from skimage import data, exposure, img_as_float
import matplotlib.pyplot as plt
image = img_as_float(data.moon())
gam1= exposure.adjust_gamma(image, 2) #調(diào)暗
gam2= exposure.adjust_gamma(image, 0.5) #調(diào)亮plt.figure('adjust_gamma',figsize=(8,8))
plt.subplot(131)plt.title('origin image')
plt.imshow(image,plt.cm.gray)plt.axis('off')
plt.subplot(132)
plt.title('gamma=2')
plt.imshow(gam1,plt.cm.gray)
plt.axis('off')
plt.subplot(133)
plt.title('gamma=0.5')
plt.imshow(gam2,plt.cm.gray)
plt.axis('off')
plt.show()

2、log對(duì)數(shù)調(diào)整

這個(gè)剛好和gamma相反

原理:I=log(I)

from skimage import data, exposure, img_as_float
import matplotlib.pyplot as plt
image = img_as_float(data.moon())
gam1= exposure.adjust_log(image) #對(duì)數(shù)調(diào)整
plt.figure('adjust_gamma',figsize=(8,8))
plt.subplot(121)plt.title('origin image')
plt.imshow(image,plt.cm.gray)
plt.axis('off')
plt.subplot(122)
plt.title('log')
plt.imshow(gam1,plt.cm.gray)
plt.axis('off')
plt.show()

3、判斷圖像對(duì)比度是否偏低

函數(shù):is_low_contrast(img)

返回一個(gè)bool型值

from skimage import data, exposure
image =data.moon()
result=exposure.is_low_contrast(image)
print(result)

輸出為False

4、調(diào)整強(qiáng)度

函數(shù):

skimage.exposure.rescale_intensity(image, in_range='image', out_range='dtype')

in_range 表示輸入圖片的強(qiáng)度范圍,默認(rèn)為'image', 表示用圖像的最大/最小像素值作為范圍

out_range 表示輸出圖片的強(qiáng)度范圍,默認(rèn)為'dype', 表示用圖像的類型的最大/最小值作為范圍
默認(rèn)情況下,輸入圖片的[min,max]范圍被拉伸到[dtype.min, dtype.max],如果dtype=uint8, 那么

dtype.min=0, dtype.max=255

import numpy as np
from skimage import exposure
image = np.array([51, 102, 153], dtype=np.uint8)
mat=exposure.rescale_intensity(image)
print(mat)

輸出為[ 0 127 255]

即像素最小值由51變?yōu)?,最大值由153變?yōu)?55,整體進(jìn)行了拉伸,但是數(shù)據(jù)類型沒有變,還是uint8

前面我們講過(guò),可以通過(guò)img_as_float()函數(shù)將unit8類型轉(zhuǎn)換為float型,實(shí)際上還有更簡(jiǎn)單的方法,就是乘以1.0

import numpy as np
image = np.array([51, 102, 153], dtype=np.uint8)
print(image*1.0)

即由[51,102,153]變成了[ 51. 102. 153.]

而float類型的范圍是[0,1],因此對(duì)float進(jìn)行rescale_intensity 調(diào)整后,范圍變?yōu)閇0,1],而不是[0,255]

import numpy as np
from skimage import exposure
image = np.array([51, 102, 153], dtype=np.uint8)
tmp=image*1.0
mat=exposure.rescale_intensity(tmp)
print(mat)

結(jié)果為[ 0. 0.5 1. ]

如果原始像素值不想被拉伸,只是等比例縮小,就使用in_range參數(shù),如:

import numpy as np
from skimage import exposure
image = np.array([51, 102, 153], dtype=np.uint8)
tmp=image*1.0
mat=exposure.rescale_intensity(tmp,in_range=(0,255))
print(mat)

輸出為:[ 0.2 0.4 0.6],即原像素值除以255

如果參數(shù)in_range的[main,max]范圍要比原始像素值的范圍[min,max] 大或者小,那就進(jìn)行裁剪,如:

mat=exposure.rescale_intensity(tmp,in_range=(0,102))
print(mat)

輸出[ 0.5 1. 1. ],即原像素值除以102,超出1的變?yōu)?

如果一個(gè)數(shù)組里面有負(fù)數(shù),現(xiàn)在想調(diào)整到正數(shù),就使用out_range參數(shù)。如:

import numpy as np
from skimage import exposure
image = np.array([-10, 0, 10], dtype=np.int8)
mat=exposure.rescale_intensity(image, out_range=(0, 127))
print(mat)

輸出[ 0 63 127]

直方圖與均衡化

在圖像處理中,直方圖是非常重要,也是非常有用的一個(gè)處理要素。

在skimage庫(kù)中對(duì)直方圖的處理,是放在exposure這個(gè)模塊中。

1、計(jì)算直方圖函數(shù):

skimage.exposure.histogram(image, nbins=256)

在numpy包中,也提供了一個(gè)計(jì)算直方圖的函數(shù)histogram(),兩者大同小義。

返回一個(gè)tuple(hist, bins_center), 前一個(gè)數(shù)組是直方圖的統(tǒng)計(jì)量,后一個(gè)數(shù)組是每個(gè)bin的中間值

import numpy as np
from skimage import exposure,data
image =data.camera()*1.0
hist1=np.histogram(image, bins=2) #用numpy包計(jì)算直方圖hist2=exposure.histogram(image, nbins=2) #用skimage計(jì)算直方圖
print(hist1)
print(hist2)

輸出:

(array([107432, 154712], dtype=int64), array([ 0. , 127.5, 255. ]))
(array([107432, 154712], dtype=int64), array([ 63.75, 191.25]))

分成兩個(gè)bin,每個(gè)bin的統(tǒng)計(jì)量是一樣的,但numpy返回的是每個(gè)bin的兩端的范圍值,而skimage返回的是每個(gè)bin的中間值

2、繪制直方圖

繪圖都可以調(diào)用matplotlib.pyplot庫(kù)來(lái)進(jìn)行,其中的hist函數(shù)可以直接繪制直方圖。

調(diào)用方式:

n, bins, patches = plt.hist(arr, bins=10, normed=0, facecolor='black', edgecolor='black',alpha=1,histtype='bar')

hist的參數(shù)非常多,但常用的就這六個(gè),只有第一個(gè)是必須的,后面四個(gè)可選

arr: 需要計(jì)算直方圖的一維數(shù)組

bins: 直方圖的柱數(shù),可選項(xiàng),默認(rèn)為10

normed: 是否將得到的直方圖向量歸一化。默認(rèn)為0

facecolor: 直方圖顏色

edgecolor: 直方圖邊框顏色

alpha: 透明度

histtype: 直方圖類型,‘bar’, ‘barstacked’, ‘step’, ‘stepfilled’

返回值 :

n: 直方圖向量,是否歸一化由參數(shù)normed設(shè)定

bins: 返回各個(gè)bin的區(qū)間范圍

patches: 返回每個(gè)bin里面包含的數(shù)據(jù),是一個(gè)list

from skimage import data
import matplotlib.pyplot as plt
img=data.camera()
plt.figure("hist")
arr=img.flatten()
n, bins, patches = plt.hist(arr, bins=256, normed=1,edgecolor='None',facecolor='red') 
plt.show()

其中的flatten()函數(shù)是numpy包里面的,用于將二維數(shù)組序列化成一維數(shù)組。
是按行序列,如

mat=[[1 2 3
     4 5 6]]

經(jīng)過(guò) mat.flatten()后,就變成了

mat=[1 2 3 4 5 6]

3、彩色圖片三通道直方圖

一般來(lái)說(shuō)直方圖都是征對(duì)灰度圖的,如果要畫rgb圖像的三通道直方圖,實(shí)際上就是三個(gè)直方圖的疊加。

from skimage import data
import matplotlib.pyplot as plt
img=data.lena()
ar=img[:,:,0].flatten()
plt.hist(ar, bins=256, normed=1,facecolor='r',edgecolor='r',hold=1)
ag=img[:,:,1].flatten()
plt.hist(ag, bins=256, normed=1, facecolor='g',edgecolor='g',hold=1)
ab=img[:,:,2].flatten()
plt.hist(ab, bins=256, normed=1, facecolor='b',edgecolor='b')
plt.show()

其中,加一個(gè)參數(shù)hold=1,表示可以疊加

4、直方圖均衡化

如果一副圖像的像素占有很多的灰度級(jí)而且分布均勻,那么這樣的圖像往往有高對(duì)比度和多變的灰度色調(diào)。直方圖均衡化就是一種能僅靠輸入圖像直方圖信息自動(dòng)達(dá)到這種效果的變換函數(shù)。它的基本思想是對(duì)圖像中像素個(gè)數(shù)多的灰度級(jí)進(jìn)行展寬,而對(duì)圖像中像素個(gè)數(shù)少的灰度進(jìn)行壓縮,從而擴(kuò)展取值的動(dòng)態(tài)范圍,提高了對(duì)比度和灰度色調(diào)的變化,使圖像更加清晰。

from skimage import data,exposure
import matplotlib.pyplot as plt
img=data.moon()
plt.figure("hist",figsize=(8,8))
arr=img.flatten()
plt.subplot(221)
plt.imshow(img,plt.cm.gray) #原始圖像
plt.subplot(222)
plt.hist(arr, bins=256, normed=1,edgecolor='None',facecolor='red') #原始圖像直方圖
img1=exposure.equalize_hist(img)
arr1=img1.flatten()
plt.subplot(223)
plt.imshow(img1,plt.cm.gray) #均衡化圖像
plt.subplot(224)
plt.hist(arr1, bins=256, normed=1,edgecolor='None',facecolor='red') #均衡化直方圖
plt.show()

CLAHE

skimage.exposure.``equalize_adapthist(image, kernel_size=None, clip_limit=0.01, nbins=256)

Contrast Limited Adaptive Histogram Equalization (CLAHE).

An algorithm for local contrast enhancement, that uses histograms computed over different tile regions of the image. Local details can therefore be enhanced even in regions that are darker or lighter than most of the image.

image : (M, N[, C]) ndarray

Input image.
kernel_size: integer or list-like, optionalDefines the shape of contextual regions used in the algorithm. If iterable is passed, it must have the same number of elements as image.ndim (without color channel). If integer, it is broadcasted to each image dimension. By default, kernel_size is 1/8 of image height by 1/8 of its width.

clip_limit : float, optional

Clipping limit, normalized between 0 and 1 (higher values give more contrast).
nbins : int, optional
Number of gray bins for histogram (“data range”).

| Returns: |

out : (M, N[, C]) ndarray

Equalized image.

http://scikit-image.org/docs/dev/api/skimage.exposure.html#equalize-adapthist

from skimage import data,exposure
import matplotlib.pyplot as plt
#%matplotlib notebook
clip_limitnumber=0.01
img=data.moon()
print(img.shape)
plt.figure("hist",figsize=(8,8))
arr=img.flatten()
plt.subplot(5,2,1)
plt.title('original')
plt.imshow(img,plt.cm.gray) #原始圖像
plt.subplot(5,2,2)
plt.hist(arr, bins=256, normed=1,edgecolor='None',facecolor='red') #原始圖像直方圖
# #img1=exposure.equalize_hist(img)
# img1=exposure.equalize_hist(img)
# arr1=img1.flatten()
# plt.subplot(6,2,3)
# plt.title('equalize_hist')
# plt.imshow(img1,plt.cm.gray) #均衡化圖像
# plt.subplot(6,2,4)
# plt.hist(arr1, bins=256, normed=1,edgecolor='None',facecolor='red') #均衡化直方圖
# plt.show()
img2=exposure.equalize_adapthist(img, kernel_size=256, clip_limit=clip_limitnumber, nbins=256)
arr2=img2.flatten()
plt.subplot(5,2,3)
plt.title('equalize_adapthist-256-'+ str(clip_limitnumber))
plt.imshow(img2,plt.cm.gray) #均衡化圖像
plt.subplot(5,2,4)
plt.hist(arr2, bins=256, normed=1,edgecolor='None',facecolor='red') #均衡化直方圖
plt.show()
img3=exposure.equalize_adapthist(img, kernel_size=128, clip_limit=clip_limitnumber, nbins=256)
arr3=img3.flatten()
plt.subplot(5,2,5)
plt.title('equalize_adapthist-128-'+ str(clip_limitnumber))
plt.imshow(img3,plt.cm.gray) #均衡化圖像
plt.subplot(5,2,6)
plt.hist(arr3, bins=256, normed=1,edgecolor='None',facecolor='red') #均衡化直方圖
plt.show()
img4=exposure.equalize_adapthist(img, kernel_size=64, clip_limit=clip_limitnumber, nbins=256)
arr4=img4.flatten()
plt.subplot(5,2,7)
plt.title('equalize_adapthist-64-'+ str(clip_limitnumber))
plt.imshow(img4,plt.cm.gray) #均衡化圖像
plt.subplot(5,2,8)
plt.hist(arr4, bins=256, normed=1,edgecolor='None',facecolor='red') #均衡化直方圖
plt.show()
img5=exposure.equalize_adapthist(img, kernel_size=32, clip_limit=clip_limitnumber, nbins=256)
arr5=img5.flatten()
plt.subplot(5,2,9)
plt.title('equalize_adapthist-32-'+ str(clip_limitnumber))
plt.imshow(img5,plt.cm.gray) #均衡化圖像
plt.subplot(5,2,10)
plt.hist(arr5, bins=256, normed=1,edgecolor='None',facecolor='red') #均衡化直方圖
plt.show()

from skimage import data,exposure
import matplotlib.pyplot as plt
#%matplotlib notebook
kernel_sizenuber=64
img=data.moon()
print(img.shape)
plt.figure("hist",figsize=(8,8))
arr=img.flatten()
plt.subplot(5,2,1)
plt.title('original')
plt.imshow(img,plt.cm.gray) #原始圖像
plt.subplot(5,2,2)
plt.hist(arr, bins=256, normed=1,edgecolor='None',facecolor='red') #原始圖像直方圖
# #img1=exposure.equalize_hist(img)
# img1=exposure.equalize_hist(img)
# arr1=img1.flatten()
# plt.subplot(6,2,3)
# plt.title('equalize_hist')
# plt.imshow(img1,plt.cm.gray) #均衡化圖像
# plt.subplot(6,2,4)
# plt.hist(arr1, bins=256, normed=1,edgecolor='None',facecolor='red') #均衡化直方圖
# plt.show()
img2=exposure.equalize_adapthist(img, kernel_size=kernel_sizenuber, clip_limit=0.001, nbins=256)
arr2=img2.flatten()
plt.subplot(5,2,3)
plt.title('equalize_adapthist-'+ str(kernel_sizenuber)+'-0.001')
plt.imshow(img2,plt.cm.gray) #均衡化圖像
plt.subplot(5,2,4)
plt.hist(arr2, bins=256, normed=1,edgecolor='None',facecolor='red') #均衡化直方圖
plt.show()
img3=exposure.equalize_adapthist(img, kernel_size=kernel_sizenuber, clip_limit=0.005, nbins=256)
arr3=img3.flatten()
plt.subplot(5,2,5)
plt.title('equalize_adapthist-'+ str(kernel_sizenuber)+'-0.005')
plt.imshow(img3,plt.cm.gray) #均衡化圖像
plt.subplot(5,2,6)
plt.hist(arr3, bins=256, normed=1,edgecolor='None',facecolor='red') #均衡化直方圖
plt.show()
img4=exposure.equalize_adapthist(img, kernel_size=kernel_sizenuber, clip_limit=0.01, nbins=256)
arr4=img4.flatten()
plt.subplot(5,2,7)
plt.title('equalize_adapthist-'+ str(kernel_sizenuber)+'-0.01')
plt.imshow(img4,plt.cm.gray) #均衡化圖像
plt.subplot(5,2,8)
plt.hist(arr4, bins=256, normed=1,edgecolor='None',facecolor='red') #均衡化直方圖
plt.show()
img5=exposure.equalize_adapthist(img, kernel_size=kernel_sizenuber, clip_limit=0.05, nbins=256)
arr5=img5.flatten()
plt.subplot(5,2,9)
plt.title('equalize_adapthist-'+ str(kernel_sizenuber)+'-0.05')
plt.imshow(img5,plt.cm.gray) #均衡化圖像
plt.subplot(5,2,10)
plt.hist(arr5, bins=256, normed=1,edgecolor='None',facecolor='red') #均衡化直方圖
plt.show()

參考文獻(xiàn)

python數(shù)字圖像處理

以上就是python skimage圖像處理的詳細(xì)內(nèi)容,更多關(guān)于python skimage圖像處理的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論