python PIL.Image绘图入门

版权声明:转载需声明原创来源;如有疑问请联系qq3048871766 https://blog.csdn.net/AcSuccess/article/details/88085045

图像的色彩模式

图像一般使用RGB色彩模式,即每个像素点的颜色由红(R),绿(G),蓝(B)组成。
RGB三个颜色通道的变化和叠加得到各种颜色,R取值0-255,G取值0-255,B取值0-255
RGB形成的颜色包括了人类视力所能感知的所有颜色。

PIL三方库安装及使用

pip install pillow

图像的数组表示 图像是由像素组成的一个二维矩阵,每个元素是一个RGB值,即(R,G,B),可使用numpy数组表示

>>> from PIL import Image
>>> import numpy as np
>>> im = np.array(Image.open('example.jpg'))
>>> im
array([[[ 95,  91, 124],
        [ 96,  92, 125],
        [ 96,  92, 125],
        ...,
        [ 97,  94, 125],
        [ 97,  94, 125],
        [ 97,  94, 125]],

       [[ 96,  92, 125],
        [ 96,  92, 125],
        [ 97,  93, 126],
        ...,
        [ 98,  94, 127],
        [ 98,  94, 127],
        [ 98,  94, 127]],

       [[ 98,  94, 127],
        [ 98,  94, 127],
        [ 97,  93, 126],
        ...,
        [ 97,  93, 126],
        [ 97,  93, 126],
        [ 97,  93, 126]],

       ...,

       [[101,  97, 130],
        [101,  97, 130],
        [101,  97, 130],
        ...,
        [107, 101, 137],
        [107, 101, 137],
        [107, 101, 137]],

       [[103,  99, 132],
        [103,  99, 132],
        [103,  99, 132],
        ...,
        [102,  96, 132],
        [103,  97, 133],
        [103,  97, 133]],

       [[102,  98, 131],
        [102,  98, 131],
        [102,  98, 131],
        ...,
        [102,  96, 132],
        [102,  96, 132],
        [102,  96, 132]]], dtype=uint8)
>>> im.shape
(313, 620, 3)
>>> im.dtype
dtype('uint8')

图像是一个三维数组,维度分别是高度,宽度和像素RGB值。

利用RGB像素运算,更改图片

>>> from PIL import Image
>>> import numpy as np
>>> a = np.array(Image.open('example.jpg'))
>>> a.dtype
dtype('uint8')
>>> b = [255,255,255]-a
>>> b.dtype
dtype('int64')
>>> c = b.astype('uint8')
>>> c.dtype
dtype('uint8')
>>> im = Image.fromarray(c)
>>> im.save('new.jpg')
>>> im.show()

生成一个灰度值

>>> d = np.array(Image.open('example.jpg').convert('L'))
>>> d.dtype
dtype('uint8')
>>> d.shape
(313, 620)
>>> im = Image.fromarray(d)
>>> im.save('hui.jpg')

手绘效果图

特点分析:
1.黑白灰色
2.边界线条较重
3.相同或相近色彩趋于白色
3.略有光源效果

from PIL import Image
import numpy as np
 
a = np.asarray(Image.open('./beijing.jpg').convert('L')).astype('float')
 
depth = 10.                      # (0-100)
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
 
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('./beijingHD.jpg')

可自行尝试

原文地址

猜你喜欢

转载自blog.csdn.net/AcSuccess/article/details/88085045