图像的RGB色彩模式
red green blue 0-255
图像:由像素组成的二维矩阵,每个元素是一个rgb值
PIL pip install pillow from PIL from Image
简单实例
为了看到图片效果,代码拆开显示
# -*- coding: utf-8 -*- # @File : image_demo.py # @Date : 2018-05-06 # pillow 5.1.0 -> 4.0.0 from PIL import Image import numpy as np
bigsea.jpg
# 读取图片 img = Image.open("images/bigsea.jpg") print(img) # <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=1200x750 at 0x10105BE48> # 转为多维数组 a = np.array(img) print(a.shape, a.dtype) # (750, 1200, 3) uint8 b = [255, 255, 255 ] - a # 转为图像 im = Image.fromarray(b.astype("uint8")) # 保存 im.save("images/bigsea1.jpg")
bigsea1.jpg
# 彩色图片转灰色 c = np.array(img.convert("L")) print(c.shape, c.dtype) # (750, 1200) uint8 d = 255 - c # 取反 im2 = Image.fromarray(d.astype("uint8")) im2.save("images/bigsea2.jpg")
bigsea2.jpg
# 区间变换 e = (100/255)*c + 150 im3 = Image.fromarray(e.astype("uint8")) im3.save("images/bigsea3.jpg")
bigsea3.jpg
# 像素平方 f = 255 * (c/255)*2 im4 = Image.fromarray(f.astype("uint8")) im4.save("images/bigsea4.jpg")
bigsea4.jpg
图像的手绘效果
# -*- coding: utf-8 -*- # @File : 图像手绘效果.py # @Date : 2018-05-06 from PIL import Image import numpy as np a = np.asarray(Image.open('images/bigsea.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('images/beijingHD.jpg')
beijingHD.jpg