如何将 numpy 矩阵转换为 cv2 图像 [python]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46746973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:49:01  来源:igfitidea点击:

How to convert numpy matrix to cv2 image [python]

pythonopencvnumpycv2

提问by user2266175

I have a numpy 2d matrix which represents a colored image. This matrix has some negative and floating point numbers but of course I can display the image using imshow(my_matrix).

我有一个代表彩色图像的 numpy 2d 矩阵。这个矩阵有一些负数和浮点数,但当然我可以使用 imshow(my_matrix) 显示图像。

my_matrix_screenshot

my_matrix_screenshot

I need to perform histogram equalization to this colored image so I found a code here in stackoverflow using cv2 (OpenCV Python equalizeHist colored image) but the problem is I am unable to convert the 2d matrix to cv matrix which takes three channels for RGB.

我需要对这个彩色图像执行直方图均衡,所以我在 stackoverflow 中找到了一个使用 cv2(OpenCV Python equalizeHist 彩色图像)的代码,但问题是我无法将 2d 矩阵转换为 cv 矩阵,它需要三个通道的 RGB。

I was searching again but all I found is to convert regular 3d numpy matrix to cv2 matrix so how can numpy 2d matrix be converted to cv2 matrix which has 3 channels?

我再次搜索,但我发现的只是将常规 3d numpy 矩阵转换为 cv2 矩阵,那么如何将 numpy 2d 矩阵转换为具有 3 个通道的 cv2 矩阵?

回答by shouhuxianjian

because the numpy.ndarray is the base of cv2, so you just write the code as usual,like

因为 numpy.ndarray 是 cv2 的基础,所以你只需像往常一样编写代码,就像

img_np = np.ones([100,100])
img_cv = cv2.resize(img_np,(200,200))

you can try

你可以试试

回答by Prasad

It is better to stack the existing numpy array one above the other of its own copy than to reshape it and add the third axis. Check this code:

最好将现有的 numpy 数组堆叠在其自己副本的另一个上方,而不是重塑它并添加第三个轴。检查此代码:

import numpy as np
import matplotlib.pyplot as plt

a = np.random.rand(90, 100) # Replace this line with your 90x100 numpy array.
a = np.expand_dims(a, axis = 2)
a = np.concatenate((a, a, a), axis = 2)
print(a.shape)
# (90, 100, 3)
plt.imshow(a)
plt.show()

You will get a gray colored image.

你会得到一个灰色的图像。