Python處理圖像五個(gè)有趣場景,很實(shí)用!
有些工具用python來實(shí)現(xiàn)不一定是技術(shù)上的最優(yōu)選擇,但可能是最簡潔、最面向大眾的。
介紹幾個(gè)不錯(cuò)的處理圖像的案例,并附上代碼,盡可能讓大家能拿來就用。
1、生成手繪圖片
現(xiàn)在很多軟件可以將照片轉(zhuǎn)換成手繪形式,python也可以實(shí)現(xiàn),而且定制化更強(qiáng),可批量轉(zhuǎn)換。
這里用到pillow庫,這是非常牛逼且專業(yè)的Python圖像處理庫
原圖:
生成手繪后:
代碼:
- # -*- coding: UTF-8 -*-
- from PIL import Image
- import numpy as np
- # 原始圖片路徑
- original_image_path = "E:\\圖片\\陸家嘴.jpg"
- # 要生成的手繪圖片路徑,可自定義
- handdrawn_image_path = "E:\\圖片\\陸家嘴-手繪.jpg"
- # 加載原圖,將圖像轉(zhuǎn)化為數(shù)組數(shù)據(jù)
- a=np.asarray(Image.open(original_image_path).convert('L')).astype('float')
- depth=10.
- #取圖像灰度的梯度值
- grad=np.gradient(a)
- #取橫縱圖像梯度值
- grad_x,grad_y=grad
- grad_x=grad_x*depth/100.
- grad_y=grad_y*depth/100.
- A=np.sqrt(grad_x**2+grad_y**2+1.)
- uni_x=grad_x/A
- uni_y=grad_y/A
- uni_z=1./A
- #光源的俯視角度轉(zhuǎn)化為弧度值
- vec_el=np.pi/2.2
- #光源的方位角度轉(zhuǎn)化為弧度值
- vec_az=np.pi/4.
- #光源對x軸的影響
- dx=np.cos(vec_el)*np.cos(vec_az)
- dy=np.cos(vec_el)*np.sin(vec_az)
- dz=np.sin(vec_el)
- #光源歸一化,把梯度轉(zhuǎn)化為灰度
- b=255*(dx*uni_x+dy*uni_y+dz*uni_z)
- #避免數(shù)據(jù)越界,將生成的灰度值裁剪至0-255內(nèi)
- b=b.clip(0,255)
- #圖像重構(gòu)
- im=Image.fromarray(b.astype('uint8'))
- print('完成')
- im.save(handdrawn_image_path)
這里可以做成批量處理的轉(zhuǎn)手繪腳本,大家試試。
2、生成證件照
這里用到pillow和removebg,分別用于修改照片尺寸和摳圖。
這里removebg用到了AI技術(shù),摳圖邊緣很柔和,效果挺不錯(cuò)的。
代碼:
- # encoding=utf-8
- from PIL import Image
- from removebg import RemoveBg
- # removebg涉及到api_key,需要到其官網(wǎng)申請
- api_key = 'PysKLJueeoyK9NbJXXXXXXXXX'
- def change_bgcolor(file_in, file_out, api_key, color):
- '''
- #必須為png格式
- '''
- p, s = file_in.split(".")
- rmbg = RemoveBg(api_key, 'error.log')
- rmbg.remove_background_from_img_file(file_in)
- file_no_bg = "{}.{}_no_bg.{}".format(p, s, s)
- no_bg_image = Image.open(file_no_bg)
- x, y = no_bg_image.size
- new_image = Image.new('RGBA', no_bg_image.size, color=color)
- new_image.paste(no_bg_image, (0, 0, x, y), no_bg_image)
- new_image.save(file_out)
- # 修改照片尺寸
- def change_size(file_in, file_out, width, height):
- image = Image.open(file_in)
- resized_image = image.resize((width, height), Image.ANTIALIAS)
- resized_image.save(file_out)
- if __name__ == "__main__":
- file_in = 'E:\\girl.png'
- file_out = 'E:\\girl_cutout.png'
- # 尺寸可按需求自修改
- # change_size(file_in, file_out, width, height)
- # 換背景色
- color = (0, 125, 255)
- change_bgcolor(file_in, file_out, api_key, color)
3、生成藝術(shù)二維碼
現(xiàn)在有不少二維碼生成工具,python也有一款二維碼生成庫-myqr,可以給二維碼加上圖片背景,看起來很炫,效果如下
使用pip安裝myqr,非常簡單。
該庫可以在命令行中運(yùn)行,你只需要傳遞網(wǎng)址鏈接、圖片地址等參數(shù),就可以生成相應(yīng)的二維碼,二維碼圖片默認(rèn)保存在當(dāng)前目錄下面。
命令行輸入格式:
myqr 網(wǎng)址鏈接
比如:
- myqr https://zhuanlan.zhihu.com/pydatalysis
再按enter鍵執(zhí)行,就能生成對應(yīng)鏈接的二維碼了。
怎么融合圖片呢?很簡單,傳入圖片地址參數(shù)'-p'
比如說我d盤有一張海綿寶寶的圖片,地址是:d:\hmbb.jpg即傳入?yún)?shù)'-pd:\hmbb.jpg'在命令行鍵入:
- myqr https://zhuanlan.zhihu.com/pydatalysis -p d:\hmbb.jpg -c
執(zhí)行就能生成上圖的海綿寶寶主題二維碼了。
4、生成詞云圖
詞云圖一般用來凸顯文本關(guān)鍵詞,產(chǎn)生視覺上的焦點(diǎn),利用好詞云會(huì)讓數(shù)據(jù)更加有說服力。
python也有專門制作詞云的庫-wordcloud,能自定義顏色和形狀。
比如我用小丑的豆瓣評論做成一張?jiān)~云圖。
作詞云圖,首先要對收集文本,然后對文本做分詞處理,最后生成詞云。
這里不對前兩步做詳細(xì)解析,只給出詞云代碼:
- def wordCloudImage(wordlist,width,height,bgcolor,savepath):
- # 可以打開你喜歡的詞云展現(xiàn)背景圖
- # cloud_mask = np.array(Image.open('nezha.png'))
- # 定義詞云的一些屬性
- wc = WordCloud(
- width=width, # 圖幅寬度 900
- height=height, # 圖幅高度 3000
- background_color=bgcolor, # 背景圖分割顏色為白色 "black"
- # mask=cloud_mask, # 背景圖樣
- max_words=300, # 顯示最大詞數(shù)
- font_path='./fonts/simhei.ttf', # 顯示中文
- collocations=False,
- # min_font_size=5, # 最小尺寸
- # max_font_size=100, # 最大尺寸
- )
- # wordfile是分詞后的詞匯列表
- x = wc.generate(wordlist)
- # 生成詞云圖片
- image = x.to_image()
- # 展示詞云圖片
- image.show()
- # savepath是圖片保存地址,保存詞云圖片
- wc.to_file(savepath)
5、生成微信九宮格圖片
有段時(shí)間朋友圈比較流行九宮格圖片,就是一張圖分割成九張圖,看著似乎很文藝。
這個(gè)可以用很多軟件來做,python當(dāng)然也能實(shí)現(xiàn),只需不到50行代碼。
代碼:
- # 朋友圈九宮格圖片制作
- # encoding=utf-8
- from PIL import Image
- import sys
- # 先將input image 填充為正方形
- def fill_image(image):
- width, height = image.size
- # 選取原圖片長、寬中較大值作為新圖片的九宮格半徑
- new_image_length = width if width > height else height
- # 生產(chǎn)新圖片【白底】
- new_image = Image.new(image.mode, (new_image_length, new_image_length), color='white')
- # 將原圖粘貼在新圖上,位置為居中
- if width > height:
- new_image.paste(image, (0, int((new_image_length - height) / 2)))
- else:
- new_image.paste(image, (int((new_image_length - width) / 2), 0))
- return new_image
- # 將圖片切割成九宮格
- def cut_image(image):
- width, height = image.size
- # 一行放3張圖
- item_width = int(width / 3)
- box_list = []
- for i in range(0, 3):
- for j in range(0, 3):
- box = (j * item_width, i * item_width, (j + 1) * item_width, (i + 1) * item_width)
- box_list.append(box)
- image_list = [image.crop(box) for box in box_list]
- return image_list
- # 保存圖片
- def save_images(image_list):
- index = 1
- for image in image_list:
- image.save('e:\\圖片\\'+str(index) + '.png', 'PNG')
- index += 1
- if __name__ == '__main__':
- file_path = "e:\\圖片\\龍貓.jpg"
- image = Image.open(file_path)
- # image.show()
- image = fill_image(image)
- image_list = cut_image(image)
- print(len(image_list))
- save_images(image_list)
python還可以做很多有趣的圖像處理,大家可以玩起來!