python - 如何在 Keras Lambda 层中使用 OpenCV 函数?

标签 python opencv keras keras-layer

我正在尝试使用一个在图像上使用某些 OpenCV 函数的函数。但是我得到的数据是一个张量,我无法将它转换成图像。

def image_func(img):
     img=cv2.cvtColor(img,cv2.COLOR_BGR2YUV) 
     img=cv2.resize(img,(200,66))
     return img

model=Sequential()
model.add(Lambda(get_ideal_img,input_shape=(r,c,ch),output_shape=(r,c,ch)))

当我运行这段代码时,它会在 cvtColor 函数中抛出一个错误,指出 img 不是一个 numpy 数组。我打印出img,好像是张量。

我不知道如何将张量更改为图像,然后再返回张量。我希望模型有这一层。

如果我无法通过 lambda 层实现此目的,我还能做什么?

最佳答案

您将 Lambda 层中的符号运算与 python 函数中的数值运算混淆了。

基本上,您的自定义操作接受数字输入但不接受符号输入。要解决此问题,您需要类似 py_func 的东西在 tensorflow

此外,您还没有考虑反向传播。简而言之,尽管该层是非参数且不可学习的,但您还需要注意其梯度。

import tensorflow as tf
from keras.layers import Input, Conv2D, Lambda
from keras.models import Model
from keras import backend as K
import cv2

def image_func(img):
    img=cv2.cvtColor(img,cv2.COLOR_BGR2YUV) 
    img=cv2.resize(img,(200,66))
    return img.astype('float32')

def image_tensor_func(img4d) :
    results = []
    for img3d in img4d :
        rimg3d = image_func(img3d )
        results.append( np.expand_dims( rimg3d, axis=0 ) )
    return np.concatenate( results, axis = 0 )

class CustomLayer( Layer ) :
    def call( self, xin )  :
        xout = tf.py_func( image_tensor_func, 
                           [xin],
                           'float32',
                           stateful=False,
                           name='cvOpt')
        xout = K.stop_gradient( xout ) # explicitly set no grad
        xout.set_shape( [xin.shape[0], 66, 200, xin.shape[-1]] ) # explicitly set output shape
        return xout
    def compute_output_shape( self, sin ) :
        return ( sin[0], 66, 200, sin[-1] )

x = Input(shape=(None,None,3))
f = CustomLayer(name='custom')(x)
y = Conv2D(1,(1,1), padding='same')(x)

model = Model( inputs=x, outputs=y )
print model.summary()

现在您可以使用一些虚拟数据测试该层。

a = np.random.randn(2,100,200,3)
b = model.predict(a)
print b.shape

model.compile('sgd',loss='mse')
model.fit(a,b)

关于python - 如何在 Keras Lambda 层中使用 OpenCV 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42883501/

相关文章:

keras - 如何通过 keras 在 tensorboard 的同一张图上显示训练损失和验证损失?

python - Keras 的 NaN 随机搜索的调谐器分数

javascript - AJAX 数据被发送到错误的 Django View

python - 3D numpy 数组的每个元素的高效一维线性回归

python - 使用Python打印当前工作目录中对象的路径

c++ - OpenCV/Tesseract:如何用 GDI+ 位图替换 libpng、libtiff 等(通过 GDI+ 加载到 cv::Mat)

c++ - 如何在opencv中找到一条线的终点?

python - 如何使用 Pandas 获取每行中的最后 n 个值

C++ OpenCV cv::Mat 的最大存储容量

python - 我如何知道我的神经网络模型是否过拟合(Keras)