参考链接: NumPy官网

参考链接: NumPy: the absolute basics for beginners

参考链接: Quickstart tutorial

参考链接: Broadcasting广播

参考链接: NumPy 中文教程

参考链接: Python数据分析与展示

背景介绍:

图像一般使用RGB色彩模式,即每个像素点的颜色由红(R)、绿(G)、蓝(B)组成
RGB三个颜色通道的变化和叠加得到各种颜色,其中
• R 红色,取值范围,0‐255
• G 绿色,取值范围,0‐255
• B 蓝色,取值范围,0‐255
RGB形成的颜色包括了人类视力所能感知的所有颜色。
PIL库,即 Python Image Library
PIL库是一个具有强大图像处理能力的第三方库
在命令行下的安装方法: pip install pillow
导入方式:   from PIL import Image
Image是PIL库中代表一个图像的类(对象)
图像是一个由像素组成的二维矩阵,每个元素是一个RGB值
图像是一个三维数组,维度分别是高度、宽度和像素RGB值

实验A:图像的各通道像素转换

import numpy as np
from PIL import Image


# 实验0
# Maradona.jpg
# 图片属性:
# 分辨率 749x966
# 宽度749像素 
# 高度966像素
im = np.array(Image.open("Maradona.jpg"))
print(im.shape,im.dtype) 
# 输出:(966, 749, 3) uint8
# (高度,宽度,通道数) 无符号8位整数 即0-255



# 实验1 求各通道的补
a = np.array(Image.open("Maradona.jpg"))
# print(a.shape,a.dtype) 

b = np.array([255,255,255])
b = [255,255,255] - a  # 求得各通道的补
im_complementary = Image.fromarray(b.astype("uint8"))
im_complementary.save("Maradona_complementary.jpg")



# 实验2 转为灰度图:
# L = R * 299/1000 + G * 587/1000+ B * 114/1000 
a = np.array(Image.open("Maradona.jpg").convert("L")) # 转为灰度图
b = a  
im_greyscale = Image.fromarray(b.astype("uint8"))
im_greyscale.save("Maradona_greyscale.jpg")



# 实验3 转为灰度求补图:
# L = R * 299/1000 + G * 587/1000+ B * 114/1000 
a = np.array(Image.open("Maradona.jpg").convert("L")) # 转为灰度图
b = [255] - a  
im_greyscale_complementary = Image.fromarray(b.astype("uint8"))
im_greyscale_complementary.save("Maradona_greyscale_complementary.jpg")



# 实验4 转为区间变换:
# L = R * 299/1000 + G * 587/1000+ B * 114/1000 
a = np.array(Image.open("Maradona.jpg").convert("L")) # 转为灰度图
b = (100/255) * a + 150 # 区间变换 
im_greyscale_RangeScale = Image.fromarray(b.astype("uint8"))
im_greyscale_RangeScale.save("Maradona_greyscale_RangeScale.jpg")



# 实验5 像素平方:
# L = R * 299/1000 + G * 587/1000+ B * 114/1000 
a = np.array(Image.open("Maradona.jpg").convert("L")) # 转为灰度图
b = 255 * (a/255) ** 2 # 区间变换 
im_greyscale_PixelSquared = Image.fromarray(b.astype("uint8"))
im_greyscale_PixelSquared.save("Maradona_greyscale_PixelSquared.jpg")

实验B:图像的手绘风格

#e17.1Pic.py
from PIL import Image
import numpy as np

im = Image.open('Maradona.jpg').convert('L')  # 转为灰度图
a = np.asarray(im).astype('float')

depth = 10.0 # (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)

im2 = Image.fromarray(b.astype('uint8')) #重构图像
im2.save("Maradona_HandDraw.jpg")

实验结果展示:

本文地址:https://blog.csdn.net/m0_46653437/article/details/110260044