2013-05-16 47 views
0

我想用cv2 LUT在Python中执行图像传输。 LUT需要与图像具有相同数量的通道。但我解决不了一个错误:多通道LUT opencv2 python声明错误

image1Transfered = cv2.LUT(image1, lut) cv2.error: /build/buildd/opencv-2.3.1/modules/core/src/convert.cpp:1037: error: (-215) (lutcn == cn || lutcn == 1) && lut.total() == 256 && lut.isContinuous() && (src.depth() == CV_8U || src.depth() == CV_8S) in function LUT

这里是Python代码,我相信我能分割图像到多个单通道和分别适用的LUT。但这是资源的浪费。

#!/usr/bin/python 
    import sys 
    import cv2 
    import numpy as np 

    image1 = cv2.imread("../pic1.jpg", 1) 
    # apply look up table 
    lut = np.arange(255, -1, -1, dtype = image1.dtype) 
    lut = np.column_stack((lut, lut, lut)) 
    image1Converted = cv2.LUT(image1, lut) # <-- this is where it fails 

谢谢你的时间。

回答

2

您正在使用np.column_stack()创建3通道图像,但这不是正确的功能。您必须使用np.dstack()cv2.merge()。然后它工作正常。

如:

In [3]: x 
array([[0, 1, 2], 
     [3, 4, 5], 
     [6, 7, 8]]) 

In [5]: np.column_stack((x,x,x)) 
array([[0, 1, 2, 0, 1, 2, 0, 1, 2], 
     [3, 4, 5, 3, 4, 5, 3, 4, 5], 
     [6, 7, 8, 6, 7, 8, 6, 7, 8]]) 

In [6]: np.dstack((x,x,x)) 
array([[[0, 0, 0], 
     [1, 1, 1], 
     [2, 2, 2]], 

     [[3, 3, 3], 
     [4, 4, 4], 
     [5, 5, 5]], 

     [[6, 6, 6], 
     [7, 7, 7], 
     [8, 8, 8]]]) 

In [11]: cv2.merge((x,x,x)) 
array([[[0, 0, 0], 
     [1, 1, 1], 
     [2, 2, 2]], 

     [[3, 3, 3], 
     [4, 4, 4], 
     [5, 5, 5]], 

     [[6, 6, 6], 
     [7, 7, 7], 
     [8, 8, 8]]], dtype=int32) 
0

谢谢阿比德,我喜欢你的博客。我正在通过你一个接一个的Python简历。这对学习Python opencv非常有帮助。你做了非常好的工作。

这里是我结束了:

lut3 = np.column_stack((lut, lut, lut)) 
lutIdxDot = np.array([0, 1, 2], dtype=int) 
lutIdx0 = np.zeros(image1.shape[0] * image1.shape[1], dtype=int) 
lutIdx1 = np.ones(image1.shape[0] * image1.shape[1], dtype=int) 
lutIdx2 = lutIdx1 * 2 
lutIdx = np.column_stack((lutIdx0, lutIdx1, lutIdx2)) 
lutIdx.shape = image1.shape 

image1Rev = lut3[image1, lutIdx] # numpy indexing will generate the expected LUT result. 

我用numpy的索引,以获取结果。我没有使用cv LUT功能。我的表现是未知的。

最后一行代码最初对我来说很陌生。索引是numpy的一个非常有趣的功能。当代码运行到最后一行时,LUT3是:

ipdb> p lut3 
array([[255, 255, 255], 
     [254, 254, 254], 
     [253, 253, 253], 
     [252, 252, 252], 
     ... 
     [ 2, 2, 2], 
     [ 1, 1, 1], 
     [ 0, 0, 0]], dtype=uint8) 

ipdb> p lutIdx 
array([[[0, 1, 2], 
     [0, 1, 2], 
     [0, 1, 2], 
     ..., 
     ..., 
     [0, 1, 2], 
     [0, 1, 2], 
     [0, 1, 2]]]) 

lutIdx有图像1的相同的形状。 lut3 [image1,lutIdx]要求一个数组,因为它的形状与image1和lutIdx相同。它的值来自lut3。对于image1的每个项目,使用lut [image1的该点的值,lutIdx的该点的值]来查找该输出值。 (我希望我能画出一张图)。