Ferguzz
Ferguzz

Reputation: 6107

flip order of ndarray in cython for opencv - OpenCV Error

Apologies for the length of the post...

I am using cython to wrap some cpp code for image processing.

On return of my processed image which is in 32-bit ARGB mode - i.e. a 32-bit uint where r = (buff[0] >> 16) & 0xFF; g = (buff[0] >> 8) & 0xFF; g = buff[0] & 0xFF, I read the data into a ndarray using a python object as suggested in the manual here: http://docs.scipy.org/doc/numpy/user/c-info.how-to-extend.html using the following class:

cdef class DataPointer:
    cdef void* data_ptr
    cdef int size

    cdef set_data(self, int size, void* data_ptr):
        self.size = size
        self.data_ptr = data_ptr

    def __array__(self):
        return np.PyArray_SimpleNewFromData(2, [self.size,4], np.NPY_UINT8, self.data_ptr)

and the following calls:

    cdef np.ndarray image

    data = DataPointer()
    data.set_data(height*width, <void*>im_buff)

    image = np.array(data, copy=False)
    image.base = <PyObject*> data
    Py_INCREF(data)

This gives me an array where each row is seperate ARGB values and so has shape (height*width, 4). They look like this:

[ 67 115 138   1]

Where these values correspond to B G R A.

Now if I go ahead and do

original = np.delete(image, 3, 1).reshape((height, width, 3)
cv2.imshow('out', original)

It works fine, however the RGB values are reversed as BGR and so the image looks a funny colour.

However when I try to flip the values like so:

original = np.fliplr(np.delete(image, 3, 1)).reshape((height, width, 3))
print original [0, :3]
cv2.imshow('out', original)

I get the following correct RGB values printed but the error message from cv2.imshow()

[[138 115  67]
[138 114  68]
[136 110  64]]
OpenCV Error: Bad flag (parameter or structure field) (Unrecognized or unsupported array type) in cvGetMat, file /Users/Tom/Desktop/OpenCV-2.4.0/modules/core/src/array.cpp, line 2482

Any idea why??

Upvotes: 0

Views: 532

Answers (1)

Andrey Kamaev
Andrey Kamaev

Reputation: 30152

It fails because of bug in OpenCV: http://code.opencv.org/issues/1393

You should be able to workaround this issue by multiplying flipped matrix by 1:

original = original * 1

Upvotes: 1

Related Questions