視頻資料:https://tv.sohu.com/v/dXMvMzM1OTQyMDI2LzExMzQxMDY1MS5zaHRtbA==.html
視頻的內容介紹:一張照片,橫着切成若干條,並且沒有打亂,隨後隔條分成了兩份,然後把這兩份各自拼接在一起,出現了跟兩張原圖一模一樣的圖片,將兩張圖豎着切成若干條,並且沒有打亂,隨後隔條分成了四份,出現了四張跟原圖一模一樣的圖片(等比例縮小)
目標:使用Python實現圖片切割拼接實驗
效果:效果如下圖所示,證實這個實驗是真的,只不過處理後的像素降低了
原理:
Numpy對圖像的處理實際上就是對ndarray的處理。圖像和ndarray又有什麼關係呢?圖像是可以用ndarray數組來表示。如圖我們可以用plt.imread()讀取一張圖片的數據,返回的就是這張圖片的ndarray數組。通過對ndarray的處理實現圖片操作
步驟解析:
【1】圖片讀取
讀取一、PIL庫
的image
import numpy as np# pip install numpy
import PIL.Image as img# pip install PIL
data=np.array(img.open('test.jpg'))
讀取二、matplotlib
庫的pyplot
import numpy as np # pip install numpy
import matplotlib.pyplot as plt # pip install matplotlib
data=plt.imread('test.jpg')
# 查看數組的形狀
data.shape
# (800,800,3),
# 第一個800代表圖片的像素寬度-縱軸像素,
# 第二個800代表圖片的像素長度-橫軸像素,
#3代表RGB通道數,(有些圖片格式是3通道,有些圖片格式是4通道)
【2】圖片切割 & 數組拼接
#圖像切割——橫軸切
width=data.shape[1]
width0= np.split(data,range(10,width,10),axis=1)
width1=width0[::2]
width2=width0[1::2]
#數組的拼接——1軸|縱軸
test1 = np.concatenate(width1,axis=1)
test2 = np.concatenate(width2,axis=1)
print(test1.shape)
plt.imshow(test1)
#對切割後的test1再進行縱軸切割
length=test1.shape[0]
length0= np.split(test1,range(10,length,10),axis=0)#test1 test2的length和原圖等長
length1=length0[::2]
length2=length0[1::2]
#數組的拼接——0軸|橫軸
test3 = np.concatenate(length1,axis=0)
test4 = np.concatenate(length2,axis=0)
print(test3.shape)
plt.imshow(test3)
【3】圖片保存
保存一、scipy.misc
import scipy.misc
scipy.misc.imsave('test3.jpg',test3)
保存二、PIL庫
的image
#image
img.fromarray(test3).save("test3.jpg")
保存三、matplotlib
庫的pyplot
plt.imsave("test3.jpg",test3)
完整代碼:整理定義了一個函數
import numpy as np # pip install numpy
import matplotlib.pyplot as plt # pip install matplotlib
jpg_path='test.jpg'
#n爲切割的大小,n越大,像素越小
def cut_jpg(jpg_path,n):
# 讀取圖片
data=plt.imread(jpg_path)
#圖像切割_橫軸切
width=data.shape[1]
width0= np.split(data,range(n,width+1,n),axis=1)#左閉右開所以+1
width1=width0[::2]
width2=width0[1::2]
#數組的拼接
test1 = np.concatenate(width1,axis=1)
test2 = np.concatenate(width2,axis=1)
#圖像切割_縱軸切
length=test1.shape[0]
#test1 test2的length和原圖等長,可以嘗試同時切割
length0= np.split(test1,range(n,length+1,n),axis=0)#左閉右開所以+1
length1=length0[::2]
length2=length0[1::2]
#數組的拼接
test3 = np.concatenate(length1,axis=0)
test4 = np.concatenate(length2,axis=0)
return test3
#返回處理後的數組對象,test1,test2,test3,test4都是一樣的,此處返回一組即可
test3=cut_jpg(jpg_path,5)
#保存圖片
plt.imsave("test305.jpg",test3)