Leo Leo - 5 months ago 17
Python Question

Color space conversion with cv2

I'm migrating from

cv
to
cv2
and I'm having difficulties finding an equivalent of the
cv.CvtColor
function.

I read in the documentation that
cv2.cvtColor
existed but I don't know how to use the third parameter.

cv2.CV_BGR2Lab
doesn't exist. Neither does
cv2.CV2_BGR2Lab
and when I use
cv.CV_BGR2Lab
all I get is an error:

cv2.cvtColor(img, img, cv.CV_BGR2Lab)


TypeError: only length-1 arrays can be converted to Python scalars


A simple piece of code that produces the problem:

img = cv2.imread(path)
cv2.cvtColor(img, img, cv.CV_BGR2Lab)

Answer

I think you just have the parameters in the wrong order. The cv2 docs show them in this order: cv2.cvtColor(src, code[, dst[, dstCn]]), which is different from what it was in cv, where the order is: cv.CvtColor(src, dst, code).

So, based on that, along with the information in the other answer regarding color conversion constants name changes, you'd need to use:

cv2.cvtColor(img, cv2.COLOR_BGR2LAB, img)