8

I have an image that I load using cv2.imread(). This returns an NumPy array. However, I need to pass this into a 3rd party API that requires the data in IplImage format.

I've scoured everything I could and I've found instances of converting from IplImage to CvMat,and I've found some references to converting in C++, but not from NumPy to IplImage in Python. Is there a function that is provided that can do this conversion?

1
  • Is it okay with Numpy --> cvMat? Commented Jul 17, 2012 at 18:03

2 Answers 2

15

You can do like this.

source = cv2.imread() # source is numpy array 
bitmap = cv.CreateImageHeader((source.shape[1], source.shape[0]), cv.IPL_DEPTH_8U, 3)
cv.SetData(bitmap, source.tostring(), 
           source.dtype.itemsize * 3 * source.shape[1])

bitmap here is cv2.cv.iplimage

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Froyo, this gets me an IplImage, but the image seems to be corrupt. Instead of using cv.CreateImageHeader and cv.SetData, I'm using cv2.cv.CreateImageHearder and cv2.cv.SetData, do you think that makes a difference?
Actually I figured it out, the tile I was trying to convert was binary, not BGR, so that's why it was getting corrupt. So I changed 3 to 1 and it worked perfectly. Thanks again for pointing me in the right direction. In case anyone else needs it, the OpenCV Cookbook has info on how to convert at opencv.willowgarage.com/wiki/PythonInterface
0

2-way to apply:

  1. img = cv2.imread(img_path) img_buf = cv2.imencode('.jpg', img)[1].tostring()

  2. just read the image file: img_buf = open(img_path, 'rb').read()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.