Mael Abgrall
Mael Abgrall

Reputation: 475

convert rgb image from numpy array to HSV (opencv)

When I'm converting an image from RGB to HSV, if the image come straight from opencv, everything is alright:

img = cv2.imread(path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

However, if this image come from a numpy array of shape (nb_of_images, 224, 224, 3) there is some complications.

Here is my import function:

def import_images(path_list):
    path_len = len(path_list)
    images = numpy.zeros((path_len, 224, 224, 3), dtype = numpy.float64)

    for pos in range(path_len):
        testimg = cv2.imread(path_list[pos])

        if(testimg is not None):
            testimg = cv2.cvtColor(testimg, cv2.COLOR_BGR2RGB)
            testimg = cv2.resize(testimg, (224, 224))
            images[pos, :, :, :] = testimg
    return images

And now, here is my trouble:

images = import_images(["./test/dog.jpg"])
img = images[0, :, :, :]
img = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)

The console give the following error:

cv2.error: /io/opencv/modules/imgproc/src/color.cpp:11073: error: (-215) depth == 0 || depth == 2 || depth == 5 in function cvtColor

I tried to change the image type:

img.astype(numpy.float32)

but the console give the same error

What am I missing ?

--edit--

I'm using python 3.5

numpy (1.14.2)

opencv-python (3.4.0.12)

Upvotes: 2

Views: 2137

Answers (1)

Dan Mašek
Dan Mašek

Reputation: 19051

The problem is with the datatype of the elements in images. Right now it's np.float64.

Let's look at the assert in the C++ source code

CV_Assert( depth == CV_8U || depth == CV_16U || depth == CV_32F );

Translated to numpy, this means the data type of elements has to be np.uint8, np.uint16, or np.float32 for cvtColor to work at all. There are other more specific checks for some of the color conversions as well.

As you mention that 32 bit floats are sufficient for your use-case, you can do

images = numpy.zeros((path_len, 224, 224, 3), dtype = numpy.float32)

Upvotes: 2

Related Questions