2011-09-28 19 views
18

Sto provando a convertire un array Numpy 2D, che rappresenta un'immagine in bianco e nero, in un array OpenCV a 3 canali (ovvero un'immagine RGB).Conversione di Numpy Array su OpenCV Array

Sulla base code samples e the docs sto cercando di farlo tramite Python come:

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) 

Tuttavia, la chiamata a CvtColor() sta gettando il seguente livello cpp Eccezione:

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 

Cosa sto sbagliando?

+0

Da i documenti per 'CvtColor'" src - L'immagine sorgente, senza segno a 8 bit, senza segno a 16 bit (CV_16UC ...) o virgola mobile a precisione singola ". Ho notato che il tuo array numpy è 'np.uint32'. Questo potrebbe spiegare 'Errore OpenCV: il passaggio Immagine è errato() in cvSetData'. Osservo che gli esempi di codice usano un tipo di dati diverso: si veda 'vis = np.zeros ((max (h1, h2), w1 + w2), np.uint8)'. –

risposta

19

Il codice può essere fissato come segue:

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) 

Breve spiegazione:

  1. np.uint32 tipo di dati non è supportato da OpenCV (supporta uint8, int8, uint16, int16, int32, float32 , float64)
  2. cv.CvtColor non può gestire gli array numpy s o entrambi gli argomenti devono essere convertiti in tipo OpenCV. cv.fromarray effettua questa conversione.
  3. Entrambi gli argomenti di cv.CvtColor devono avere la stessa profondità. Quindi ho cambiato il tipo di sorgente in float a 32 bit per abbinare il ddestination.

Inoltre vi consiglio di utilizzare la versione più recente di OpenCV pitone API perché utilizza le matrici NumPy come principale tipo di dati:

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

Grazie per il vostro aiuto. Era esattamente così. – Cerin

-1

Questo è ciò che ha funzionato per me ...

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)