图片去雾代码
时间: 2023-09-03 13:16:36 浏览: 39
以下是一个基于 Python 和 OpenCV 的简单图片去雾代码示例:
```python
import cv2
import numpy as np
# 读取原始图像和大气光照图像
img = cv2.imread("hazy_image.jpg")
atmosphere = cv2.imread("atmosphere.jpg")
# 将图像从 BGR 色彩空间转换到 HSV 色彩空间
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# 提取亮度分量
value = hsv[:,:,2]
# 计算暗通道图像
kernel_size = 15
dark_channel = cv2.erode(value, cv2.getStructuringElement(cv2.MORPH_RECT, (kernel_size, kernel_size)))
min_filter = cv2.minFilter2D(dark_channel, -1, np.ones((kernel_size, kernel_size)))
dark_channel = min_filter
# 估计全局大气光照值
top_percent = 0.001
height, width = dark_channel.shape
num_pixels = int(height * width * top_percent)
dark_channel_flat = dark_channel.reshape(height * width)
indices = dark_channel_flat.argsort()[-num_pixels:]
atmosphere_flat = np.zeros((height * width), dtype=np.uint8)
atmosphere_flat[indices] = atmosphere.reshape(height * width)[indices]
atmosphere = atmosphere_flat.reshape((height, width))
# 估计透射率
A = 0.1 # 环境光照的强度
transmission = 1 - A * dark_channel / atmosphere
# 线性增强透射率
max_transmission = 0.8
min_transmission = 0.1
transmission = np.clip(transmission, min_transmission, max_transmission)
transmission = (transmission - min_transmission) / (max_transmission - min_transmission)
# 恢复图像
radiance = np.zeros(img.shape, dtype=np.uint8)
for i in range(3):
radiance[:,:,i] = np.clip((img[:,:,i] - atmosphere[i]) / transmission + atmosphere[i], 0, 255)
# 显示结果
cv2.imshow("Original Image", img)
cv2.imshow("Dehazed Image", radiance)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
上述代码中,我们首先读取了原始图像和大气光照图像,然后将图像从 BGR 色彩空间转换到 HSV 色彩空间,提取亮度分量,计算暗通道图像,估计全局大气光照值,估计透射率,线性增强透射率,最后恢复图像。需要注意的是,这里的代码只是一个示例,具体实现可能还需要进行一些调整和改进。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)