如何使用Opencv 2.4将python numpy数组转换为RGB图像? [英] How to convert a python numpy array to an RGB image with Opencv 2.4?
问题描述
我已经搜索了类似的问题,但是没有发现任何有用的信息,因为大多数解决方案都使用旧版本的OpenCV.
I have searched for similar questions, but haven't found anything helpful as most solutions use older versions of OpenCV.
我有一个3D numpy数组,我想使用OpenCV(cv2)将其显示和/或保存为BGR图像.
I have a 3D numpy array, and I would like to display and/or save it as a BGR image using OpenCV (cv2).
作为一个简短的例子,假设我有:
As a short example, suppose I had:
import numpy, cv2
b = numpy.zeros([5,5,3])
b[:,:,0] = numpy.ones([5,5])*64
b[:,:,1] = numpy.ones([5,5])*128
b[:,:,2] = numpy.ones([5,5])*192
我想做的就是将b保存并显示为类似于以下内容的彩色图像:
What I would like to do is save and display b as a color image similar to:
cv2.imwrite('color_img.jpg', b)
cv2.imshow('Color image', b)
cv2.waitKey(0)
cv2.destroyAllWindows()
这不起作用,大概是因为b的数据类型不正确,但是经过大量搜索之后,我不知道如何将其更改为正确的数据.如果您可以提供任何指针,将不胜感激!
This doesn't work, presumably because the data type of b isn't correct, but after substantial searching, I can't figure out how to change it to the correct one. If you can offer any pointers, it would be greatly appreciated!
推荐答案
您不需要将NumPy
数组转换为Mat
,因为OpenCV cv2
模块可以接受NumPy
数组.
您唯一需要关心的是{0,1}映射到{0,255},并且NumPy
数组中任何大于1的值都等于255.因此,应在代码中除以255,如下所示
You don't need to convert NumPy
array to Mat
because OpenCV cv2
module can accept NumPy
array.
The only thing you need to care for is that {0,1} is mapped to {0,255} and any value bigger than 1 in NumPy
array is equal to 255. So you should divide by 255 in your code, as shown below.
img = numpy.zeros([5,5,3])
img[:,:,0] = numpy.ones([5,5])*64/255.0
img[:,:,1] = numpy.ones([5,5])*128/255.0
img[:,:,2] = numpy.ones([5,5])*192/255.0
cv2.imwrite('color_img.jpg', img)
cv2.imshow("image", img)
cv2.waitKey()
这篇关于如何使用Opencv 2.4将python numpy数组转换为RGB图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!