python把图片变成素描样子
import tkinter as tk
from tkinter import *
from tkinter import filedialog, messagebox
from PIL import Image, ImageFilter, ImageOps, ImageTk
realPath = ""
def selectPicture():
global realPath
root = tk.Tk()
root.withdraw()
Fpath = filedialog.askopenfilename() #我们选择的图片的路径
path.set(Fpath) #把路径信息写到文本框中
realPath = Fpath #更新我们的路径
def dodge(a, b, alpha):
return min(int(a*255/(256-b*alpha)),255)
def draw(blur=25):
img = Image.open(realPath)
LastIndex = realPath.rfind('.') #后缀里面的.出现的位置
FevalPath = realPath[: LastIndex] #保存时需要把后缀除去,加上 sumiao.png
alpha = scale1.get()
alpha = float(alpha)
img1 = img.convert('L') #调用Image模块里面的convert函数将图片转换成灰色
img2 = img1.copy()
img2 = ImageOps.invert(img2)
for i in range(blur): #模糊度
img2 = img2.filter(ImageFilter.BLUR)
width, height = img1.size
for x in range(width) :
for y in range( height):
a = img1.getpixel((x, y))
b = img2.getpixel((x, y))
img1. putpixel((x, y), dodge(a, b, alpha))
img1.show()
img1.save(FevalPath + 'sumiao.png')
def closeWindow():
window.destroy() # destroy是注销
sys.exit(0) #退出进程
def getValue(self):
val = scale1.get() #得到滑块的值
value.set(str(val)) #将其送到后面文本框中显示
#draw(img)
window = Tk() # Tk是一个类
window.title("图片转为素描") # 窗口标题
window.geometry('480x230') # 窗口大小
window.geometry('+500+240') # 窗口位置
path = StringVar() #似乎可编辑文本框的必须是这个类型才可以用set,有待查找资料
Label(window,text ="目标路径:").grid(row = 0, column = 0)
Entry(window, text = path,width=40).grid(row = 0, column = 1) #可编辑文本
#设置滑动条
Label(window,text ="模糊程度:").grid(row = 1, column = 0) #设置标签
scale1 = tk.Scale(window, from_=0, to=1.0, orient=tk.HORIZONTAL,resolution=0.01,show=0,command=getValue, length=200)
scale1.grid(row=1, column=1)
value =StringVar()
scale1.set(0.93) #设置默认值
Entry(window, text = value,width=10).grid(row = 1, column = 2) #可编辑文本
# 按钮控制,command作为点击触发的事件
btn = Button(window, text="选择图片",width=10, height=1,command=selectPicture) #第一个按钮
btn.grid(row=0, column=2)
btn1 = Button(window, text="开始转换", width=10, height=1, command=draw) #第二个按钮
btn1.grid(row=2, column=1)
btn2 = Button(window, text="退出", width=10, height=1, command=closeWindow) #第三个按钮
btn2.grid(row=2, column=2, sticky=E, padx=7)
window.protocol("WM_DELETE_WINDOW", closeWindow) # protocol() 用户关闭窗口触发的事件
window.mainloop() # 显示窗口,也叫消息循环
本来想上传视频的,但是发现不可以上传,我上传一张图片吧,这个效果大概是这样