How to combine a RGB image with a Grayed image in opencv?

白昼怎懂夜的黑 提交于 2019-12-13 07:30:03

问题


I refered this link to combine two images, and it works if both images are being RGB formated

Combining Two Images with OpenCV

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?


回答1:


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.

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)

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.



来源:https://stackoverflow.com/questions/42920201/how-to-combine-a-rgb-image-with-a-grayed-image-in-opencv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!