图像的手绘效果实例分析
图像的数组表示
以下代码请在Anaconda的IPython平台运行
PIL库的安装:
在命令行下的安装方法:pip install pillow
from PIL import Image #Image是PIL库中代表一个图像的类(对象)
from PIL import Image
import numpy as np
im = array(Image.open("C:/01.jpg"))
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-3-8a130c29210a> in <module>
----> 1 im = array(Image.open("C:/01.jpg"))
NameError: name 'array' is not defined
im = np.array(Image.open("C:/01.jpg"))
print(im.shape,im.dtype)
(2448, 1836, 3) uint8 #图像是一个三维数组,维度分别是高度·宽度和像素RGB值
图像的变换
读入图像后,获得像素RGB值,修改后保存为新的文件
from PIL import Image
import numpy as np
a = np.array(Image.open("D:/01.jpg"))
print(a.shape,a.dtype)
(2448, 1836, 3) uint8
b = [255,255,255] -a
im = Image.fromarray(b.astype('uint8'))
im.save("D:/02.jpg")
from PIL import Image
import numpy as np
a = array(Image.open("D:/01.jpg").convert('L'))
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-3-5e990d68fb86> in <module>
----> 1 a = array(Image.open("D:/01.jpg").convert('L'))
NameError: name 'array' is not defined
a = np.array(Image.open("D:/01.jpg").convert('L'))
b = 255 - a
im = Image.fromarray(b.astype('uint8'))
im.save("D:/03.jpg")
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-7-79fa9e4b0e79> in <module>
----> 1 im.save("D:/03.jpg")
~\anaconda3\lib\site-packages\PIL\Image.py in save(self, fp, format, **params)
2097 fp = builtins.open(filename, "r+b")
2098 else:
-> 2099 fp = builtins.open(filename, "w+b")
2100
2101 try:
FileNotFoundError: [Errno 2] No such file or directory: 'D:/03.jpg' #注意代码书写格式规范,这个是错误案例
im.save("D:/03.jpg")
from PIL import Image
import numpy as np
a = np.array(Image.open("D:/01.jpg").convert('L'))
c = (100/255)*a + 150 #区间变换
im = Image.fromarray(c.astype('uint8'))
im.save("D:/04.jpg")
from PIL import Image
import numpy as np
a = np.array(Image.open("D:/01.jpg").convert('L'))
d = 255 * (a/255)**2 #像素平方
im = Image.fromarray(d.astype('uint8'))
im.save("D:/05.jpg")
"图像的手绘效果"实例分析
from PIL import Image
import numpy as np
a = np.asarray(Image.open('D:/01.jpg').convert('L')).astype('float')
depth = 10. #(0-100)
grad = np.gradient(a) #取图像灰度的梯度值
grad_x,grad_y = grad #分别取横纵图像梯度值
grad_x = grad_y*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
vec_el = np.pi/2.2 #光源的俯视角度,弧度值
vec_az = np.pi/4. #光源的方位角度,弧度值
dx = np.cos(vec_el)*np.cos(vec_az) #光源对x轴的影响
dy = np.cos(vec_el)*np.sin(vec_az) #光源对y轴的影响
dz = np.sin(vec_el) #光源对z轴的影响
b = 255*(dx*uni_x + dy*uni_y + dz*uni_z) #光源归一化
b = b.clip(0,255)
im = Image.fromarray(b.astype('uint8')) #重构图像
im.save('D:/HD.jpg')