如何在opencv中将RGB图像与灰色图像结合在一起? [英] How to combine a RGB image with a Grayed image in opencv?
问题描述
我引用了此链接以合并两个图像,并且如果两个图像都采用RGB格式也可以使用
I refered this link to combine two images, and it works if both images are being RGB formated
问题是,既然RGB图像是三维,而灰度图像是二维,那么如何将RGB图像与灰色图像结合起来?
The question is how to combine a RGB image with a Grayed image, since the RGB image is three dimensions but gray image is two dimensions?
推荐答案
RGB图像是3维的,而灰度图像是2维的.为了使组合成为可能,您需要向灰度图像添加一维.如果x
是2维数组x
,则将其转换为3维数组的最简单方法是x[:, :, None]
.或者,您可以使用NumPy的 atleast_3D
.
RGB images are 3-dimensional whereas grayscale images are 2-dimensional. In order for the combination to be possible, you need to add one dimension to the grayscale image. If x
is a 2-dimensional array x
, the simplest way to transform it into a 3-dimensional array is x[:, :, None]
. Alternatively, you could use NumPy's atleast_3D
.
下面的代码使用NumPy和scikit-image库完成工作:
The code below gets the job done using NumPy and scikit-image libraries:
import numpy as np
from skimage import io
rgb = io.imread('https://i.stack.imgur.com/R6X5p.jpg')
gray = io.imread('https://i.stack.imgur.com/f27t5.png')
rows_rgb, cols_rgb, channels = rgb.shape
rows_gray, cols_gray = gray.shape
rows_comb = max(rows_rgb, rows_gray)
cols_comb = cols_rgb + cols_gray
comb = np.zeros(shape=(rows_comb, cols_comb, channels), dtype=np.uint8)
comb[:rows_rgb, :cols_rgb] = rgb
comb[:rows_gray, cols_rgb:] = gray[:, :, None]
io.imshow(comb)
请注意,上面的示例假定两个图像均为np.uint8
类型.如果没有,则应使用适当的类型转换.
It is important to note that the example above assumes that both images are of type np.uint8
. If not, you should use appropriate type conversions.
这篇关于如何在opencv中将RGB图像与灰色图像结合在一起?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!