python的Image庫非常強大,幾乎被認爲是python官方圖像處理庫。這裏簡單的介紹幾種我自己最近用到的處理,包括位移、剪切和遮擋。以後再用到其他功能,就繼續更新吧。
1、位移
Imagechops模塊除了offset這個偏移方法,還有很多函數,見這裏。
def shift(im):
plt.figure()
plt.subplot(1,2,1)
img = Image.open(im)
plt.imshow(img)
img2 = ImageChops.offset(img,200,100) # 水平位移:200,垂直位移:100
plt.subplot(1,2,2)
plt.imshow(img2)
plt.show()
#img = img.resize((224, 224), resample=Image.LANCZOS)
return img2
2、遮擋
# 遮擋
def paste(im):
plt.figure()
plt.subplot(1, 2, 1)
img = Image.open(im)
plt.imshow(img)
img2 = img.crop((0,0,80,80)) #裁剪原圖中一部分作爲覆蓋圖片
img.paste(img2, (150, 150, 150+img2.size[0], 150+img2.size[1])) #第二個參數是覆蓋位置
plt.subplot(1, 2, 2)
plt.imshow(img)
plt.show()
return img
3、剪切
#剪切
def shear(im):
plt.figure()
plt.subplot(1, 2, 1)
img = Image.open(im)
plt.imshow(img)
#image = cv2.resize(image,(224,224))
cropped = img.crop((100,100,500,500)) #座標從左上開始
plt.subplot(1, 2, 2)
plt.imshow(cropped)
plt.show()
return cropped
完整代碼
本篇鏈接:
https://blog.csdn.net/weixin_42385606/article/details/105995928