![cover](https://img-blog.csdnimg.cn/img_convert/6caf7fbef0004759a791b91e9214ce6e.png)
Opencv或者Image实现单通道(灰度图)转换为RGB三通道图像展示并保存(原理+代码)
opencv
OpenCV: 开源计算机视觉库
项目地址:https://gitcode.com/gh_mirrors/opencv31/opencv
![](https://devpress.csdnimg.cn/6deffb34f7114cc1a2e1e686a67e0027.png)
·
一、原理介绍
该转换过程实际上就是将单通道图像复制3次,分别作为RGB三个通道,从而创建一个看似彩色但实际上每个颜色通道都相同的图像
二、代码如下
Opencv实现:
import cv2
# 读取单通道图像(灰度图)
img_gray = cv2.imread('img.png', cv2.IMREAD_GRAYSCALE)
# 检查图像是否成功加载
if img_gray is None:
print("Error loading image")
exit()
# 使用OpenCV转换图像到RGB
img_rgb = cv2.cvtColor(img_gray, cv2.COLOR_GRAY2RGB)
# 显示原图(灰度图)
cv2.imshow('Original Gray Image', img_gray)
# 显示转换后的RGB图像
cv2.imshow('Converted to RGB', img_rgb)
# 保存转换后的RGB图像
output_file = 'imageRGB.png'
cv2.imwrite(output_file, img_rgb)
print(f"Image saved as {output_file}")
# 等待按键后关闭所有窗口
cv2.waitKey(0)
cv2.destroyAllWindows()
Image代码实现:
from PIL import Image
# 打开图像(默认模式下PIL会自动检测图像模式,如果是灰度图则为'L'模式)
img_gray = Image.open('your_image.png')
# 转换为RGB图像
# 注意:对于灰度图,直接使用.convert()转为"RGB"模式并不会增加色彩信息,每个像素的R=G=B=灰度值
img_rgb = img_gray.convert('RGB')
# 显示图像
img_rgb.show(title='Converted to RGB')
# 保存转换后的图像
output_file = 'converted_image.png'
img_rgb.save(output_file)
print(f"Image saved as {output_file}")
![]( https://profile-avatar.csdnimg.cn/default.jpg)
![](https://devpress.csdnimg.cn/7174e1ca86c447029bb12f9ec0bd281c.png)
![](https://devpress.csdnimg.cn/096f7827187446559bd7b6030eb5db38.png)
![](https://devpress.csdnimg.cn/6deffb34f7114cc1a2e1e686a67e0027.png)
OpenCV: 开源计算机视觉库
最近提交(Master分支:4 个月前 )
1d701d16
Don't overflow pointer addition 1 天前
e76924ef
In both cases we add negative value (as unsigned type), so
pointer addition wraps, which is undefined behavior.
1 天前
更多推荐
所有评论(0)