pillow与numpy实现图片素描化

from PIL import Image
import numpy as np

#封装一个图像处理类
class TestNumpy(object):
    def photo2paint(self,img_url):
        # 读取图片
        my_photo = np.asarray(Image.open(img_url).convert("L")).astype("float")
        # print(my_photo.shape)
        #设置灰度阈值(范围0~100)
        depth = 40
        # 将灰度系数映射到numpy
        grad = np.gradient(my_photo)
        #获取坐标
        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
        #设置x轴和y轴
        dx = np.cos(vec_el)* np.cos(vec_az)
        dy = np.cos(vec_el)* np.sin(vec_az)
        #设置z轴
        dz = np.sin(vec_el)
        #设置byte值
        b = 255*(dx*uni_x+dy*uni_y+dz*uni_z)
        #光源归一化
        b = b.clip(0,255)
        #声明图像类图像
        im = Image.fromarray(b.astype("uint8"))
        #保存图像
        im.save("./test_new.jpg")
if __name__ == "__main__":
    testnumpy = TestNumpy()
    testnumpy.photo2paint('./test_numpy.jpg')
    

 

posted @ 2019-03-09 09:52  Xcsg  Views(763)  Comments(0Edit  收藏  举报