10

i want to create a multichannel mat object in python with cv2 opencv wrapper.

i've found examples on the net where the c++ Mat::zeros is replaced with numpy.zeros, that seems good. but no multichannel type seems to fit..

look at the code:

import cv2
import numpy as np

size = 200, 200
m = np.zeros(size, dtype=np.uint8) # ?
m = cv2.cvtColor(m, cv2.COLOR_GRAY2BGR)
p1 = (0,0)
p2 = (200, 200)
cv2.line(m, p1, p2, (0, 0, 255), 10)

cv2.namedWindow("draw", cv2.CV_WINDOW_AUTOSIZE)
while True:
    cv2.imshow("draw", m)

    ch = 0xFF & cv2.waitKey(1)
    if ch == 27:
        break
cv2.destroyAllWindows()

i want to avoid m = cv2.cvtColor(m, cv2.COLOR_GRAY2BGR) but neither cv2.CV_8UC3 np.uin32 works.

some hint?

nkint
  • 11,513
  • 31
  • 103
  • 174

1 Answers1

23

Try this as size:

size = 200, 200, 3
m = np.zeros(size, dtype=np.uint8)

Basically what I did to find what arguments I need for the matrix is:

img = cv2.imread('/tmp/1.jpg')
print img.shape, img.dtype
# (398, 454, 3), uint8

But one could probably find it in OpenCV documentation as well.

gatto
  • 2,947
  • 1
  • 21
  • 24
  • where in the documentation please? – nkint Apr 26 '13 at 13:59
  • Hm, I can't find any official opencv docs on this, which states clearly that you have to do it this way, I guess it's a "common knowledge" that you need 3 layers/dimensions for a color image. However I was able to find [this](http://stackoverflow.com/questions/12881926/create-a-new-rgb-opencv-image-using-python) SO question. – gatto Apr 26 '13 at 14:21