当我将图像从RGB转换为HSV时,如果图像直接来自opencv,则一切正常:
img = cv2.imread(path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
但是,如果此图像来自形状(nb_of_images,224,224,3(的numpy数组,则会出现一些复杂性。
这是我的导入函数:
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
现在,这是我的麻烦:
images = import_images(["./test/dog.jpg"])
img = images[0, :, :, :]
img = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
控制台给出以下错误:
cv2.error: /io/opencv/modules/imgproc/src/color.cpp:11073: error: (-215) depth == 0 || depth == 2 || depth == 5 in function cvtColor
我尝试更改图像类型:
img.astype(numpy.float32)
但是控制台给出了相同的错误
我错过了什么?
--编辑--
我正在使用蟒蛇 3.5
numpy (1.14.2(
OpenCV-Python (3.4.0.12(
问题出在 images
中元素的数据类型上。现在它np.float64
.
让我们看一下C++源代码中的断言
CV_Assert( depth == CV_8U || depth == CV_16U || depth == CV_32F );
翻译成numpy
,这意味着元素的数据类型必须np.uint8
、np.uint16
或np.float32
才能cvtColor
工作。对于某些颜色转换,还有其他更具体的检查。
正如您提到的,32 位浮点数足以满足您的用例,您可以这样做
images = numpy.zeros((path_len, 224, 224, 3), dtype = numpy.float32)