【问题标题】:convert rgb image from numpy array to HSV (opencv)将 rgb 图像从 numpy 数组转换为 HSV(opencv)
【发布时间】:2018-09-28 20:24:10
【问题描述】:

当我将图像从 RGB 转换为 HSV 时,如果图像直接来自 opencv,则一切正常:

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

但是,如果此图像来自形状为 numpy 的数组 (nb_of_images, 224, 224, 3),则会出现一些复杂情况。

这是我的导入函数:

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)

【问题讨论】:

  • 可能是this帮助你!
  • @RickM。也许最后一个答案,其余的都是使用古老的已弃用的 opencv API。
  • @DanMašek 很难确定,因为 OP 没有提到 API 版本。 @Mel Abgrall 这行也可能有问题images[pos, :, :, :] = testimg
  • @RickM。对版本进行了编辑。什么样的问题会导致 images[pos, :, :, :] = testimg ?
  • @RickM。考虑到 OP 只使用新的 API,这并不难。

标签: python numpy opencv


【解决方案1】:

问题在于images 中元素的数据类型。现在是np.float64

我们看看C++ source code中的断言

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

转换为numpy,这意味着元素的数据类型必须是np.uint8np.uint16np.float32cvtColor 才能正常工作。对于某些颜色转换,还有其他更具体的检查。

正如您提到 32 位浮点数足以满足您的用例,您可以这样做

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

【讨论】:

  • 在函数 import_images 中修改了这一行:images = numpy.zeros((path_len, 224, 224, 3), dtype = numpy.float32)
猜你喜欢
  • 1970-01-01
  • 2010-12-14
  • 1970-01-01
  • 2018-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-28
  • 1970-01-01
相关资源
最近更新 更多