Python圖像處理

做者|Garima Singh
編譯|VK
來源|Git Connectedhtml

之前照相歷來沒有那麼容易。如今你只須要一部手機。拍照是免費的,若是咱們不考慮手機的費用的話。就在上一代人以前,業餘藝術家和真正的藝術家若是拍照很是昂貴,而且每張照片的成本也不是免費的。python

咱們拍照是爲了及時保存偉大的時刻,被保存的記憶隨時準備在將來被"打開"。git

就像醃製東西同樣,咱們要注意正確的防腐劑。固然,手機也爲咱們提供了一系列的圖像處理軟件,可是一旦咱們須要處理大量的照片,咱們就須要其餘的工具。這時,編程和Python就派上用場了。Python及其模塊如Numpy、Scipy、Matplotlib和其餘特殊模塊提供了各類各樣的函數,可以處理大量圖片。spring

爲了向你提供必要的知識,本章的Python教程將處理基本的圖像處理和操做。爲此,咱們使用模塊NumPy、Matplotlib和SciPy。編程

咱們從scipy包misc開始。數組

# 如下行僅在Python notebook中須要:
%matplotlib inline
from scipy import misc
ascent = misc.ascent()
import matplotlib.pyplot as plt
plt.gray()
plt.imshow(ascent)
plt.show()

除了圖像以外,咱們還能夠看到帶有刻度的軸。這多是很是有趣的,若是你須要一些關於大小和像素位置的方向,但在大多數狀況下,你想看到沒有這些信息的圖像。咱們能夠經過添加命令plt.axis("off")來去掉刻度和軸:機器學習

from scipy import misc
ascent = misc.ascent()
import matplotlib.pyplot as plt
plt.axis("off") # 刪除軸和刻度
plt.gray()
plt.imshow(ascent)
plt.show()

咱們能夠看到這個圖像的類型是一個整數數組:函數

ascent.dtype

輸出:工具

dtype('int64')學習

咱們也能夠檢查圖像的大小:

ascent.shape

輸出:

(512,512)

misc包裏還有一張浣熊的圖片:

import scipy.misc
face = scipy.misc.face()
print(face.shape)
print(face.max)
print(face.dtype)
plt.axis("off")
plt.gray()
plt.imshow(face)
plt.show()
(768, 1024, 3)
<built-in method max of numpy.ndarray object at 0x7f9e70102800>
uint8
import matplotlib.pyplot as plt

matplotlib只支持png圖像

img = plt.imread('frankfurt.png')
print(img[:3])
[[[ 0.41176471  0.56862748  0.80000001]
  [ 0.40392157  0.56078434  0.79215688]
  [ 0.40392157  0.56862748  0.79607844]
  ..., 
  [ 0.48235294  0.62352943  0.81960785]
  [ 0.47843137  0.627451    0.81960785]
  [ 0.47843137  0.62352943  0.82745099]]
 [[ 0.40784314  0.56470591  0.79607844]
  [ 0.40392157  0.56078434  0.79215688]
  [ 0.40392157  0.56862748  0.79607844]
  ..., 
  [ 0.48235294  0.62352943  0.81960785]
  [ 0.47843137  0.627451    0.81960785]
  [ 0.48235294  0.627451    0.83137256]]
 [[ 0.40392157  0.56862748  0.79607844]
  [ 0.40392157  0.56862748  0.79607844]
  [ 0.40392157  0.56862748  0.79607844]
  ..., 
  [ 0.48235294  0.62352943  0.81960785]
  [ 0.48235294  0.62352943  0.81960785]
  [ 0.48627451  0.627451    0.83137256]]]
plt.axis("off")
imgplot = plt.imshow(img)
lum_img = img[:,:,1]
print(lum_img)
[[ 0.56862748  0.56078434  0.56862748 ...,  0.62352943  0.627451
   0.62352943]
 [ 0.56470591  0.56078434  0.56862748 ...,  0.62352943  0.627451    0.627451  ]
 [ 0.56862748  0.56862748  0.56862748 ...,  0.62352943  0.62352943
   0.627451  ]
 ..., 
 [ 0.31764707  0.32941177  0.32941177 ...,  0.30588236  0.3137255
   0.31764707]
 [ 0.31764707  0.3137255   0.32941177 ...,  0.3019608   0.32156864
   0.33725491]
 [ 0.31764707  0.3019608   0.33333334 ...,  0.30588236  0.32156864
   0.33333334]]
plt.axis("off")
imgplot = plt.imshow(lum_img)

色彩、色度和色調

如今,咱們將展現如何給圖像着色。色彩是色彩理論的一種表達,是畫家經常使用的一種技法。想到畫家而不想到荷蘭是很難想象的。因此在下一個例子中,咱們使用荷蘭風車的圖片。

windmills = plt.imread('windmills.png')
plt.axis("off")
plt.imshow(windmills)

輸出:

<matplotlib.image.AxesImage at 0x7f9e77f02f98>

咱們如今想給圖像着色。咱們用白色,這將增長圖像的亮度。爲此,咱們編寫了一個Python函數,它接受一個圖像和一個百分比值做爲參數。設置"百分比"爲0不會改變圖像,設置爲1表示圖像將徹底變白:

import numpy as np
import matplotlib.pyplot as plt
def tint(imag, percent):
    """
    imag: 圖像
    percent: 0,圖像將保持不變,1,圖像將徹底變白色,值應該在0~1
    """
    tinted_imag = imag + (np.ones(imag.shape) - imag) * percent
    return tinted_imag
windmills = plt.imread('windmills.png')
tinted_windmills = tint(windmills, 0.8)
plt.axis("off")
plt.imshow(tinted_windmills)

輸出:

<matplotlib.image.AxesImage at 0x7f9e6cd99978>

陰影是一種顏色與黑色的混合,它減小了亮度。

import numpy as np
import matplotlib.pyplot as plt
def shade(imag, percent):
    """
    imag: 圖像
    percent: 0,圖像將保持不變,1,圖像將徹底變黑,值應該在0~1
    """
    tinted_imag = imag * (1 - percent)
    return tinted_imag
windmills = plt.imread('windmills.png')
tinted_windmills = shade(windmills, 0.7)
plt.imshow(tinted_windmills)

輸出:

<matplotlib.image.AxesImage at 0x7f9e6cd20048>
def vertical_gradient_line(image, reverse=False):
    """
    咱們建立一個垂直梯度線。形狀 (1, image.shape[1], 3))
    若是reverse爲False,則值從0增長到1,
    不然,值將從1遞減到0。
    """
    number_of_columns = image.shape[1]
    if reverse:
        C = np.linspace(1, 0, number_of_columns)
    else:
        C = np.linspace(0, 1, number_of_columns)
    C = np.dstack((C, C, C))
    return C
horizontal_brush = vertical_gradient_line(windmills)
tinted_windmills =  windmills * horizontal_brush
plt.axis("off")
plt.imshow(tinted_windmills)

輸出:

<matplotlib.image.AxesImage at 0x7f9e6ccb3d68>

如今,咱們將經過將Python函數的reverse參數設置爲「True」來從右向左着色圖像:

def vertical_gradient_line(image, reverse=False):
    """
    咱們建立一個水平梯度線。形狀 (1, image.shape[1], 3))
    若是reverse爲False,則值從0增長到1,
    不然,值將從1遞減到0。
    """
    number_of_columns = image.shape[1]
    if reverse:
        C = np.linspace(1, 0, number_of_columns)
    else:
        C = np.linspace(0, 1, number_of_columns)
    C = np.dstack((C, C, C))
    return C
horizontal_brush = vertical_gradient_line(windmills, reverse=True)
tinted_windmills =  windmills * horizontal_brush
plt.axis("off")
plt.imshow(tinted_windmills)

輸出:

<matplotlib.image.AxesImage at 0x7f9e6cbc82b0>
def horizontal_gradient_line(image, reverse=False):
    """
    咱們建立一個垂直梯度線。形狀(image.shape[0], 1, 3))
    若是reverse爲False,則值從0增長到1,
    不然,值將從1遞減到0。
    """
    number_of_rows, number_of_columns = image.shape[:2]
    C = np.linspace(1, 0, number_of_rows)
    C = C[np.newaxis,:]
    C = np.concatenate((C, C, C)).transpose()
    C = C[:, np.newaxis]
    return C
vertical_brush = horizontal_gradient_line(windmills)
tinted_windmills =  windmills 
plt.imshow(tinted_windmills)

輸出:

<matplotlib.image.AxesImage at 0x7f9e6cb52390>

色調是由一種顏色與灰色的混合產生的,或由着色和陰影產生的。

charlie = plt.imread('Chaplin.png')
plt.gray()
print(charlie)
plt.imshow(charlie)
[[ 0.16470589  0.16862746  0.17647059 ...,  0.          0.          0.        ]
 [ 0.16078432  0.16078432  0.16470589 ...,  0.          0.          0.        ]
 [ 0.15686275  0.15686275  0.16078432 ...,  0.          0.          0.        ]
 ..., 
 [ 0.          0.          0.         ...,  0.          0.          0.        ]
 [ 0.          0.          0.         ...,  0.          0.          0.        ]
 [ 0.          0.          0.         ...,  0.          0.          0.        ]]

輸出:

<matplotlib.image.AxesImage at 0x7f9e70047668>

給灰度圖像着色:http://scikit-image.org/docs/dev/auto_examples/plot_tinting_grayscale_images.html

在下面的示例中,咱們將使用不一樣的顏色映射。顏色映射能夠在matplotlib.pyplot.cm.datad中找到:

plt.cm.datad.keys()

輸出:

dict_keys(['afmhot', 'autumn', 'bone', 'binary', 'bwr', 'brg', 'CMRmap', 'cool', 'copper', 'cubehelix', 'flag', 'gnuplot', 'gnuplot2', 'gray', 'hot', 'hsv', 'jet', 'ocean', 'pink', 'prism', 'rainbow', 'seismic', 'spring', 'summer', 'terrain', 'winter', 'nipy_spectral', 'spectral', 'Blues', 'BrBG', 'BuGn', 'BuPu', 'GnBu', 'Greens', 'Greys', 'Oranges', 'OrRd', 'PiYG', 'PRGn', 'PuBu', 'PuBuGn', 'PuOr', 'PuRd', 'Purples', 'RdBu', 'RdGy', 'RdPu', 'RdYlBu', 'RdYlGn', 'Reds', 'Spectral', 'YlGn', 'YlGnBu', 'YlOrBr', 'YlOrRd', 'gist_earth', 'gist_gray', 'gist_heat', 'gist_ncar', 'gist_rainbow', 'gist_stern', 'gist_yarg', 'coolwarm', 'Wistia', 'Accent', 'Dark2', 'Paired', 'Pastel1', 'Pastel2', 'Set1', 'Set2', 'Set3', 'tab10', 'tab20', 'tab20b', 'tab20c', 'Vega10', 'Vega20', 'Vega20b', 'Vega20c', 'afmhot_r', 'autumn_r', 'bone_r', 'binary_r', 'bwr_r', 'brg_r', 'CMRmap_r', 'cool_r', 'copper_r', 'cubehelix_r', 'flag_r', 'gnuplot_r', 'gnuplot2_r', 'gray_r', 'hot_r', 'hsv_r', 'jet_r', 'ocean_r', 'pink_r', 'prism_r', 'rainbow_r', 'seismic_r', 'spring_r', 'summer_r', 'terrain_r', 'winter_r', 'nipy_spectral_r', 'spectral_r', 'Blues_r', 'BrBG_r', 'BuGn_r', 'BuPu_r', 'GnBu_r', 'Greens_r', 'Greys_r', 'Oranges_r', 'OrRd_r', 'PiYG_r', 'PRGn_r', 'PuBu_r', 'PuBuGn_r', 'PuOr_r', 'PuRd_r', 'Purples_r', 'RdBu_r', 'RdGy_r', 'RdPu_r', 'RdYlBu_r', 'RdYlGn_r', 'Reds_r', 'Spectral_r', 'YlGn_r', 'YlGnBu_r', 'YlOrBr_r', 'YlOrRd_r', 'gist_earth_r', 'gist_gray_r', 'gist_heat_r', 'gist_ncar_r', 'gist_rainbow_r', 'gist_stern_r', 'gist_yarg_r', 'coolwarm_r', 'Wistia_r', 'Accent_r', 'Dark2_r', 'Paired_r', 'Pastel1_r', 'Pastel2_r', 'Set1_r', 'Set2_r', 'Set3_r', 'tab10_r', 'tab20_r', 'tab20b_r', 'tab20c_r', 'Vega10_r', 'Vega20_r', 'Vega20b_r', 'Vega20c_r'])
import numpy as np
import matplotlib.pyplot as plt
charlie = plt.imread('Chaplin.png')
#  colormaps plt.cm.datad
# cmaps = set(plt.cm.datad.keys())
cmaps = {'afmhot', 'autumn', 'bone', 'binary', 'bwr', 'brg', 
         'CMRmap', 'cool', 'copper', 'cubehelix', 'Greens'}
X = [  (4,3,1, (1, 0, 0)), (4,3,2, (0.5, 0.5, 0)), (4,3,3, (0, 1, 0)), 
       (4,3,4, (0, 0.5, 0.5)),  (4,3,(5,8), (0, 0, 1)), (4,3,6, (1, 1, 0)), 
       (4,3,7, (0.5, 1, 0) ),               (4,3,9, (0, 0.5, 0.5)),
       (4,3,10, (0, 0.5, 1)), (4,3,11, (0, 1, 1)),    (4,3,12, (0.5, 1, 1))]
fig = plt.figure(figsize=(6, 5))
#fig.subplots_adjust(bottom=0, left=0, top = 0.975, right=1)
for nrows, ncols, plot_number, factor in X:
    sub = fig.add_subplot(nrows, ncols, plot_number)
    sub.set_xticks([])
    plt.colors()
    
    sub.imshow(charlie*0.0002, cmap=cmaps.pop())
    sub.set_yticks([])
#fig.show()

原文連接:https://levelup.gitconnected.com/image-processing-in-python-b5e3e11e1413

歡迎關注磐創AI博客站:
http://panchuang.net/

sklearn機器學習中文官方文檔:
http://sklearn123.com/

歡迎關注磐創博客資源彙總站:
http://docs.panchuang.net/

相關文章
相關標籤/搜索