📜  使用 Python-OpenCV 拆分和合并通道

📅  最后修改于: 2022-05-13 01:55:24.806000             🧑  作者: Mango

使用 Python-OpenCV 拆分和合并通道

在本文中,我们将学习如何使用Python中的 OpenCV 将多通道图像拆分为单独的通道并将这些单独的通道组合成多通道图像。

为此,我们分别使用cv2.split() 和 cv2.merge()函数。

使用的图像:



拆分频道

cv2.split() 用于将彩色/多通道图像拆分为单独的单通道图像。就性能(时间)而言, cv2.split() 是一项昂贵的操作。数组输出向量的顺序取决于输入图像的通道顺序。

例子:

Python3
# Python program to explain splitting of channels
  
# Importing cv2
import cv2 
  
# Reading the image using imread() function
image = cv2.imread('img.jpg')
  
# Displaying the original BGR image
cv2.imshow('Original_Image', image)
  
# Using cv2.split() to split channels of coloured image 
b,g,r = cv2.split(image)
  
# Displaying Blue channel image
# Blue colour is highlighted the most
cv2.imshow("Model Blue Image", b)
  
# Displaying Green channel image
# Green colour is highlighted the most
cv2.imshow("Model Green Image", g)
  
# Displaying Red channel image
# Red colour is highlighted the most
cv2.imshow("Model Red Image", r)
  
# Waits for user to press any key
cv2.waitKey(0)


Python3
# Python program to explain Merging of Channels
  
# Importing cv2
import cv2
  
# Reading the BGR image using imread() function
image = cv2.imread("img.jpg")
  
# Splitting the channels first to generate different 
# single
  
# channels for merging as we don't have separate
# channel images
b, g, r = cv2.split(image)
  
# Displaying Blue channel image
cv2.imshow("Model Blue Image", b)
  
# Displaying Green channel image
cv2.imshow("Model Green Image", g)
  
# Displaying Red channel image
cv2.imshow("Model Red Image", r)
  
# Using cv2.merge() to merge Red, Green, Blue Channels
  
# into a coloured/multi-channeled image
image_merge = cv2.merge([r, g, b])
  
# Displaying Merged RGB image
cv2.imshow("RGB_Image", image_merge)
  
# Waits for user to press any key
cv2.waitKey(0)


输出:



合并频道

cv2.merge()用于将多个单通道图像合并为彩色/多通道图像。

例子:

蟒蛇3

# Python program to explain Merging of Channels
  
# Importing cv2
import cv2
  
# Reading the BGR image using imread() function
image = cv2.imread("img.jpg")
  
# Splitting the channels first to generate different 
# single
  
# channels for merging as we don't have separate
# channel images
b, g, r = cv2.split(image)
  
# Displaying Blue channel image
cv2.imshow("Model Blue Image", b)
  
# Displaying Green channel image
cv2.imshow("Model Green Image", g)
  
# Displaying Red channel image
cv2.imshow("Model Red Image", r)
  
# Using cv2.merge() to merge Red, Green, Blue Channels
  
# into a coloured/multi-channeled image
image_merge = cv2.merge([r, g, b])
  
# Displaying Merged RGB image
cv2.imshow("RGB_Image", image_merge)
  
# Waits for user to press any key
cv2.waitKey(0)

输出: