Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HSV2BGR conversion fails in Python OpenCV script

My script is supposed to take a greyscale image and map the values to hues.

#!/usr/bin/env python

import cv2
import numpy

infile = cv2.imread('Lenna.png')

infile = infile[:,:,0]

hues = (numpy.array(infile)/255.)*179

outimageHSV = numpy.array([[[b,255,255] for b in a] for a in hues]).astype(int)

outimageBGR = cv2.cvtColor(outimageHSV, cv2.COLOR_HSV2BGR)

cv2.imshow('dst_rt', outimageBGR)
cv2.waitKey(0)
cv2.destroyAllWindows()

It fails on the line with cvtColor and I get this error:

OpenCV Error: Assertion failed (depth == CV_8U || depth == CV_16U || depth == CV_32F) in cvtColor, file /tmp/opencv20150506-38415-u2kidu/opencv-2.4.11/modules/imgproc/src/color.cpp, line 3644
Traceback (most recent call last):
  File "luma2hue.py", line 16, in <module>
    outimageBGR = cv2.cvtColor(outimageHSV, cv2.COLOR_HSV2BGR)
cv2.error: /tmp/opencv20150506-38415-u2kidu/opencv-2.4.11/modules/imgproc/src/color.cpp:3644: error: (-215) depth == CV_8U || depth == CV_16U || depth == CV_32F in function cvtColor

Do I need to do something else to my outimageHSV array to make it ready for cvtColor?

like image 843
kkjelgard Avatar asked Feb 18 '16 04:02

kkjelgard


People also ask

How do you convert BGR to HSV on OpenCV?

To choose the correct code, we need to take in consideration that, when calling the imread function, the image will be stored in BGR format. Thus, to convert to HSV, we should use the COLOR_BGR2HSV code. As output, the cvtColor will return the converted image, which we will store in a variable.

What is the purpose of cv2 cvtColor () function?

cv2. cvtColor() method is used to convert an image from one color space to another. There are more than 150 color-space conversion methods available in OpenCV.

What does cv2 cvtColor return?

It returns the Coverted color space image. The default color format in OpenCV is often referred to as RGB, but it is actually BGR (the bytes are reversed). So the first byte in a standard (24-bit) color image will be an 8-bit Blue component, the second byte will be Green, and the third byte will be Red.


2 Answers

The error message implies that cv2.cvtColor expects an image with a (color) depth of 8 or 16 bit unsigned int (8U, 16U) or 32 bit float (32F). Try changing astype(int) to astype(numpy.uint8)

like image 100
Sammelsurium Avatar answered Nov 04 '22 00:11

Sammelsurium


outimageHSV needs to be casted as uint8.

import numpy as np

outimageHSV = np.uint8(outimageHSV)
outimageBGR = cv2.cvtColor(outimageHSV, cv2.COLOR_HSV2BGR)
like image 2
Thiago Falcao Avatar answered Nov 03 '22 22:11

Thiago Falcao