编程实现图像的灰度变换 编程实现以下处理:图像变暗、图像变亮、降低对比度、gamma变换,应具有可视化输出的代码。
时间: 2024-09-09 07:09:02 浏览: 103
在Python中,我们可以使用PIL(Python Imaging Library)库来操作图像,并结合NumPy进行数值计算。下面是一个简单的示例,展示了如何实现图像的灰度变换以及所提到的几种效果:
```python
from PIL import Image
import numpy as np
# 加载图像
def load_image(file_path):
with Image.open(file_path) as img:
return np.array(img.convert('L')) # 转换为灰度图
# 图像变暗
def darken(image, factor=0.5):
return image * (1 - factor)
# 图像变亮
def lighten(image, factor=0.5):
return image + factor
# 降低对比度
def reduce_contrast(image, factor=0.5):
mean = np.mean(image)
return ((image - mean) * factor) + mean
# Gamma变换
def gamma_correction(image, gamma=1.8):
invGamma = 1.0 / gamma
table = np.array([((i / 255.0)**invGamma)*255 for i in range(256)])
return np.clip(np.round(table[image.astype(float)]), 0, 255).astype(np.uint8)
# 可视化输出
def visualize(image, title="Original"):
plt.imshow(image, cmap='gray')
plt.title(title)
plt.show()
# 示例
original_img = load_image("path_to_your_image.jpg")
darkened = darken(original_img)
lightened = lighten(original_img)
reduced_contrast = reduce_contrast(original_img)
corrected = gamma_correction(original_img)
visualize(original_img, "Original")
visualize(darkened, "Darkened")
visualize(lightened, "Lightened")
visualize(reduced_contrast, "Reduced Contrast")
visualize(corrected, "Gamma Correction")
阅读全文