首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将Numpy数组转换为OpenCV数组

将Numpy数组转换为OpenCV数组
EN

Stack Overflow用户
提问于 2011-09-29 02:03:46
回答 2查看 145.5K关注 0票数 45

我正在尝试将代表黑白图像的2DNumpy数组转换为3通道OpenCV数组(即RGB图像)。

基于code samplesthe docs,我尝试通过Python实现这一点,如下所示:

代码语言:javascript
运行
复制
import numpy as np, cv
vis = np.zeros((384, 836), np.uint32)
h,w = vis.shape
vis2 = cv.CreateMat(h, w, cv.CV_32FC3)
cv.CvtColor(vis, vis2, cv.CV_GRAY2BGR)

但是,对CvtColor()的调用抛出了以下cpp级别的异常:

代码语言:javascript
运行
复制
OpenCV Error: Image step is wrong () in cvSetData, file /build/buildd/opencv-2.1.0/src/cxcore/cxarray.cpp, line 902
terminate called after throwing an instance of 'cv::Exception'
  what():  /build/buildd/opencv-2.1.0/src/cxcore/cxarray.cpp:902: error: (-13)  in function cvSetData

Aborted

我做错了什么?

EN

回答 2

Stack Overflow用户

发布于 2017-10-06 17:05:38

这就是对我有效的..。

代码语言:javascript
运行
复制
import cv2
import numpy as np

#Created an image (really an ndarray) with three channels 
new_image = np.ndarray((3, num_rows, num_cols), dtype=int)

#Did manipulations for my project where my array values went way over 255
#Eventually returned numbers to between 0 and 255

#Converted the datatype to np.uint8
new_image = new_image.astype(np.uint8)

#Separated the channels in my new image
new_image_red, new_image_green, new_image_blue = new_image

#Stacked the channels
new_rgb = np.dstack([new_image_red, new_image_green, new_image_blue])

#Displayed the image
cv2.imshow("WindowNameHere", new_rgbrgb)
cv2.waitKey(0)
票数 6
EN

Stack Overflow用户

发布于 2020-05-27 17:49:50

最简单的解决方案是使用Pillow lib:

代码语言:javascript
运行
复制
from PIL import Image

image = Image.fromarray(<your_numpy_array>.astype(np.uint8))

你可以把它当做图像来使用。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7587490

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档