Python 数字图像处理之图像光照效果的实现
工具:VS Code、图像文件
Python模块:cv2、math、numpy
https://imgblog.csdnimg.cn/e725acecc8da448c9eafddc5ad608a1e.jpg?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5LiA5Y-q5bCP55m977yB,size_20,color_FFFFFF,t_70,g_se,x_16)]](https://i-blog.csdnimg.cn/blog_migrate/1e742ba4ec0722a93ac21ceabb340b6a.jpeg)
1. 导入相应的Python模块
import cv2 #用以读取图像文件
import math
import numpy as np
2. 读取图像文件
img=cv2.imread("111.jpg") #参数为图像文件名
3. 获取图像的高和宽(行列值)
rows,cols = img.shape[:2]
注:[0:2]是切片的意思,.shape 应当是OpenCV模块中处理图片的,是图片的一个属性,这个属性是个列表 ,然后对这个列表切片操作。
例子:h,w = img.shape[:2] 获取彩色图片的高、宽,并且赋值给h和w;如果是h,w,v = img.shape[:3] 获取彩色图片的高、宽、通道,并赋值给h w v
此处转自:https://blog.youkuaiyun.com/Mr_LanGX/article/details/120275615
4. 设置中心点
centerX=rows/2 #可以根据自己需求去设置XY的位置
centerY=rows/2
print(centerX,centerY)
radius = min(centerX,centerY) #增亮半径
print(radius)
运行结果:
344.0 344.0
344.0
5. 光照效果的实现
strength = 300 #自定义光照亮度
dst = np.zeros((rows,cols,3),dtype="uint8") #新建目标图像,矩阵中每个元素的类型为uint8
#图像光照特效
for i in range(rows):
for j in range(cols):
distance = math.pow((centerY-j),2)+math.pow((centerX-i),2) #计算当前点到光照中心距离
B=img[i,j][0] #获取原始图像
G=img[i,j][1]
R=img[i,j][2]
if(distance<radius*radius):
result = (int)(strength*(1.0-math.sqrt(distance)/radius)) #按照距离大小计算增强的光照值
B=img[i,j][0]+result
G=img[i,j][1]+result
R=img[i,j][2]+result
B=min(255,max(0,B)) #防止越界
G=min(255,max(0,G))
R=min(255,max(0,R))
dst[i,j]=np.uint8((B,G,R)) #生成处理后的图像
else:
dst[i,j]=np.uint8((B,G,R))
6. 显示图像
cv2.imshow('src',img)
cv2.imshow('dst',dst)
cv2.waitKey()
cv2.destroyAllWindows.destroyAllWindows()
处理结果:

本文介绍了使用Python的OpenCV库来实现图像的光照效果处理。通过读取图像,计算像素点到光照中心的距离,根据距离调整像素亮度,并确保结果在合法范围内,最终得到具有光照效果的新图像。





