将Numpy数组转换为OpenCV数组

2024-04-20 09:00:13 发布

您现在位置:Python中文网/ 问答频道 /正文

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

基于code samplesthe docs我试图通过Python这样做:

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级别的异常:

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

我做错什么了?


Tags: in图像buildnp数组opencvviscpp
2条回答

您的代码可以修复如下:

import numpy as np, cv
vis = np.zeros((384, 836), np.float32)
h,w = vis.shape
vis2 = cv.CreateMat(h, w, cv.CV_32FC3)
vis0 = cv.fromarray(vis)
cv.CvtColor(vis0, vis2, cv.CV_GRAY2BGR)

简要说明:

  1. np.uint32OpenCV不支持数据类型(它支持uint8int8uint16int16int32float32float64
  2. cv.CvtColor无法处理numpy数组,因此两个参数都必须转换为OpenCV类型。cv.fromarray执行此转换。
  3. cv.CvtColor的两个参数的深度必须相同。所以我将源类型更改为32位浮点,以匹配ddestination。

另外,我建议您使用较新版本的OpenCV python API,因为它使用numpy数组作为主要数据类型:

import numpy as np, cv2
vis = np.zeros((384, 836), np.float32)
vis2 = cv2.cvtColor(vis, cv2.COLOR_GRAY2BGR)

这就是我的工作。。。

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)

相关问题 更多 >