效果展示
原始效果圖
素描效果圖
相關依賴包
# 超美觀的打印庫
from pprint import pprint
# 圖像處理庫
from PIL import Image
# 科學計算庫
import numpy as np
# GUI文件打開窗口
import tkinter.filedialog
制作文件打開窗口
# 創建根窗口
root = tkinter.Tk().withdraw()
# 文件選擇對話窗口,返回文件對象
file_ = tkinter.filedialog.askopenfilename()
pprint("1、讀取原始圖像成功")
素描圖轉換
# 加入異常處理
try:
# 定義顏色深度(0~100,值越大顏色越深)
depth = 20
# 獲取照片灰度的梯度值
image_grad = np.gradient(np.asarray(Image.open(file_).convert('L')).astype('int'))
pprint("2、獲取圖像梯度值成功")
# 分別獲取X,Y方向的梯度值,然后使用顏色深度進行處理
grad_x, grad_y = image_grad[0] * depth / 100., image_grad[1] * depth / 100.
pprint("3、顏色深度處理成功")
# 降噪基
base_ = np.sqrt(grad_x ** 2 + grad_y ** 2 + 1.)
a, b, c = grad_x / base_, grad_y / base_, 1. / base_
# 光源的俯視角度值和方位角度值
sce_z, sce_x = np.pi / 2.1, np.pi / 3
# 光源對x,y,z 軸的影響
dx, dy, dz = np.cos(sce_z) * np.cos(sce_x), np.cos(sce_z) * np.sin(sce_x), np.sin(sce_z)
# 光源歸一化
Normalized = 255 * (dx * a + dy * b + dz * c).clip(0, 255)
pprint("4、光源處理成功")
# 重新構造圖像
img = Image.fromarray(Normalized.astype('uint8'))
pprint("5、圖像重構成功")
# 保存轉換后的照片
img.save('素描圖.jpg')
pprint("6、保存轉換后的圖像成功")
except Exception:
print('對不起,圖像轉換失敗!')
exe文件打包
-F 參數代表打包文件,trans_image.py 是自己的.py文件路徑
pyinstaller -F trans_image.py
【粉絲福利】關注公眾號,獲取全套視頻資料,喜歡小編點個 '關注' 吧!
本文由微信公眾號【python 集中營】發布,更多精彩文章、視頻資料即可領取!