python处理彩色图像通道拆分与合并

彩色图像通道拆分与合并

  • 待处理图像 ML.jpg
    请添加图片描述

1. 使用 opencv

import cv2
import matplotlib.pyplot as plt
import numpy as np
# 读取图像
# 读取图像
image = cv2.imread('ML.jpg')
plt.imshow(image)
print(type(image))  # 输出:<class 'numpy.ndarray'>
print(image.shape)  # 输出:(152, 150, 3)
b,g,r = cv2.split(image)
print(b.shape,g.shape,r.shape) # 输出:(152, 150) (152, 150) (152, 150)
# 使用matplotlib显示拆分后的通道
plt.figure(figsize=(12, 4))
plt.subplot(1,3,1),plt.imshow(b,cmap='gray'),plt.title('Blue Channel')
plt.subplot(1,3,2),plt.imshow(g,cmap='gray'),plt.title('Green Channel')
plt.subplot(1,3,3),plt.imshow(r,cmap='gray'),plt.title('Red Channel')
plt.show()

在这里插入图片描述

# 保存图像
# 保存图像
cv2.imwrite('ML_cv_B.jpg',b)
cv2.imwrite('ML_cv_G.jpg',g)
cv2.imwrite('ML_cv_R.jpg',r)
print(b.shape,g.shape,r.shape)  # 输出:(152, 150) (152, 150) (152, 150)

# 在把三张单通道图像读取进来,需要设定IMREAD_GRAYSCALE,保证以单通道读取
image_b = cv2.imread('ML_cv_B.jpg',cv2.IMREAD_GRAYSCALE)
image_g = cv2.imread('ML_cv_G.jpg',cv2.IMREAD_GRAYSCALE)
image_r = cv2.imread('ML_cv_R.jpg',cv2.IMREAD_GRAYSCALE)

# 把三个单通道图像合成一个三通道图像,也就是把3个 二维矩阵堆叠成一个三维矩阵的过程 
image_bgr = cv2.merge([image_b,image_g,image_r])
# 显示合成后的图像
print(image_bgr.shape)  # 输出:(152, 150, 3)
plt.imshow(image_bgr)

2. 使用 numpy

import numpy as np
import matplotlib.pyplot as plt
from PIL import Image

# 读取图像
image = Image.open('ML.jpg')
print(image)  # 输出:<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=150x152 at 0x1D0ED6F2850>
# 转张量
arr = np.array(image)
print(arr.shape)  # 输出:(152, 150, 3)
# 切分
r,g,b = arr[:,:,0],arr[:,:,2],arr[:,:,2]
print(r.shape,g.shape,b.shape)  #输出:(152, 150) (152, 150) (152, 150)
plt.imshow(arr)

plt.subplot(131),plt.imshow(r,cmap='gray')
plt.subplot(132),plt.imshow(g,cmap='gray')
plt.subplot(133),plt.imshow(b,cmap='gray')

在这里插入图片描述

在这里插入代码片# 将NumPy数组转换为Pillow图像  
img_r = Image.fromarray(r)  
img_g = Image.fromarray(g)  
img_b = Image.fromarray(b)  
print(img_r)  # 输出:<PIL.Image.Image image mode=L size=150x152 at 0x1D0EB524C90>
# 保存
img_r.save('ML_PIL_R.jpg')
img_g.save('ML_PIL_G.jpg')
img_b.save('ML_PIL_B.jpg')

# 再读取单通道图像
image_r = Image.open('ML_PIL_R.jpg')
image_g = Image.open('ML_PIL_G.jpg')
image_b = Image.open('ML_PIL_B.jpg')
print(image_r)  # 输出:<PIL.JpegImagePlugin.JpegImageFile image mode=L size=150x152 at 0x1D0F166FDD0>
# 转张量
R,G,B = np.array(image_r),np.array(image_g),np.array(image_b)

print(R.shape,G.shape,B.shape) # 输出:(152, 150) (152, 150) (152, 150)
# 数组堆叠,升维,变成多通道图像
RGB_Image = np.stack([R,G,B],2)
print(RGB_Image.shape)  # 输出:(152, 150, 3)
# 显示图像
plt.imshow(RGB_Image)
  • 这里有个问题,重新堆叠的图像彩色没有那么鲜艳了
    在这里插入图片描述
  • 8
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MechMaster

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值