编程实现图像的分段线性灰度变换和非线性灰度变换
时间: 2023-09-20 10:11:59 浏览: 153
分段线性灰度变换:
```python
import numpy as np
from PIL import Image
def piecewise_linear(img, breakpoints, slopes):
"""
分段线性灰度变换
:param img: 原图像
:param breakpoints: 分段点
:param slopes: 斜率
:return: 变换后的图像
"""
img_arr = np.array(img)
# 计算分段线性函数
def piecewise(x):
return (slopes[0] * x) if x < breakpoints[0] else \
(slopes[-1] * x + (breakpoints[-1] - slopes[-1] * breakpoints[-1])) if x >= breakpoints[-1] else \
slopes[np.searchsorted(breakpoints, x)] * x + \
(breakpoints[np.searchsorted(breakpoints, x)] - slopes[np.searchsorted(breakpoints, x)] * breakpoints[
np.searchsorted(breakpoints, x)])
# 应用分段线性函数到图像数组
img_arr = piecewise(img_arr)
# 将图像数组转换回图像
img_out = Image.fromarray(np.uint8(img_arr))
return img_out
```
非线性灰度变换:
```python
import numpy as np
from PIL import Image
def nonlinear(img, func):
"""
非线性灰度变换
:param img: 原图像
:param func: 变换函数
:return: 变换后的图像
"""
img_arr = np.array(img)
# 应用变换函数到图像数组
img_arr = func(img_arr)
# 将图像数组转换回图像
img_out = Image.fromarray(np.uint8(img_arr))
return img_out
```
其中,变换函数 `func` 可以根据具体需求自行定义,例如:
```python
def gamma_correction(x, gamma):
"""
伽马校正变换函数
"""
return 255 * np.power(x / 255, gamma)
```
使用示例:
```python
# 加载图像
img = Image.open('lena.png')
# 分段线性灰度变换
img_out = piecewise_linear(img, [50, 150], [0.5, 1.5])
img_out.show()
# 非线性灰度变换(伽马校正)
img_out = nonlinear(img, lambda x: gamma_correction(x, 1.2))
img_out.show()
```
阅读全文