python 使用三種常用的工具包處理圖片


matplotlib,PIL(Pillow),Opencv三種常用的作圖方式。

使用matplotlib畫圖,很棒,matplotlib 是python最著名的2D繪圖庫,它提供了一整套和matlab相似的命令API,十分適合交互式地進行制圖。而且也可以方便地將它作為繪圖控件,嵌入GUI應用程序中。通過簡單的繪圖語句,就可以繪制出高質量的圖了。

pip install matplotlib
from PIL import Image
import matplotlib.pyplot as plt
img=Image.open('d:/dog.png')
plt.figure("dog")
plt.imshow(img)
plt.show()
figure默認是帶axis的,如果沒有需要,我們可以關掉
plt.axis('off')
print(img.size)  #圖片的尺寸
print(img.mode ) #圖片的模式
print(img.format)  #圖片的格式
img.save('d:/dog.jpg') #這行代碼不僅能保存圖片,還是轉換格式,如本例中,就由原來的png圖片保存為了jpg圖片。
這里在centos下跑pip install matplotlib 會出錯,提示讓你升級pip,但是centos下默認安裝的是python2.7 於是pip install --upgrade pip 但是仍然報錯
去了官網https://matplotlib.org/users/installing.html
找到解決方法,
yum install python2-matplotlib
如果是python3的話就 yum install python3-matplotlib 不過我想直接pip install matplotlib 也沒問題應該。

這個應該是numpy需要升級了。

pip install numpy --upgrade

如果還不行,pip install numpy --upgrade --ignore-installed

 

再次安裝pip install numpy

說無法安裝。。已經存在,奇怪,明明已經卸載了。(實際上下面兩行是執行不了的,只是想說明可以查看path)

import numpy print numpy.__path__

找到numpy的物理路徑,手動強制刪掉,rm -rf numpy

再次安裝,成功了。

執行,又報錯了。

import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
加上這三行,搞定。

又雙報錯了。

style_score.data[0] 改為style_score.item()

終於運行成功了,其實我只是找了份畫風遷移的代碼,運行一下而已。。原理嘛就是把一張圖的內容和風格(紋理style)分開提取特征,然后相互雜交,是不是這個理兒?
想到這里,我覺得有很多東西不是一下子就要懂得很深入,可以先了解它是什么,能干什么,至於為什么等以后需要知道的時候再知道也不遲,因為要補的知識實在太多,腦子裝不下要爆炸。

人類一思考,上天就想笑,於是又報錯了

 於是改成png,除去了A透明度,以為終於可以了。

跑去改了matplotlib的源碼,把tostring()改成了tobytes(),這只畢加索風格的貓如何?

 

使用python進行數字圖片處理,還得安裝Pillow包。雖然python里面自帶一個PIL(python images library), 但這個庫現在已經停止更新了,所以使用Pillow, 它是由PIL發展而來的。

pip install Pillow
from PIL import Image
img=Image.open('d:/dog.png')
img.show()


import matplotlib.pyplot as plt

#創建新的figure
fig = plt.figure()

#必須通過add_subplot()創建一個或多個繪圖
ax = fig.add_subplot(221)

#繪制2x2兩行兩列共四個圖,編號從1開始
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224)

#圖片的顯示
plt.show()

  熱圖(heatmap)是數據分析的常用方法,通過色差、亮度來展示數據的差異、易於理解。Python在Matplotlib庫中,調用imshow()函數實現熱圖繪制。

#coding=utf-8
import matplotlib.pyplot as plt 
import numpy as np

points = np.arange(-5,5,0.01)

xs,ys = np.meshgrid(points,points)

z = np.sqrt(xs**2 + ys**2)

#創建新的figure
fig = plt.figure()

#繪制2x2兩行兩列共四個圖,編號從1開始
ax = fig.add_subplot(221)
ax.imshow(z)

ax = fig.add_subplot(222)
#使用自定義的colormap(灰度圖)
ax.imshow(z,cmap=plt.cm.gray)

ax = fig.add_subplot(223)
#使用自定義的colormap
ax.imshow(z,cmap=plt.cm.cool)

ax = fig.add_subplot(224)
#使用自定義的colormap
ax.imshow(z,cmap=plt.cm.hot)

#圖片的顯示
plt.show()

  

Opencv 的做法

import cv2 as cv
# load 
img = cv.imread(imagepath)
# shape=(height, width, channel)
h,w,c = img.shape
# show
cv.imshow('window_title', img)
# save
cv.imwrite(savepath, img)

最后,matplotlib的官網,有很多酷炫的圖和源碼,非常推薦。

https://matplotlib.org/gallery/index.html

 


免責聲明!

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



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