我正在尝试使用一个在图像上使用某些 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/