我想在Keras模型中进行卷积运算后对图像应用过滤器。 这是我的代码。
import cv2
import glob
import numpy as np
from keras.layers import Conv2D, Input, Lambda
from keras.models import Model
images = [cv2.resize(cv2.imread(file), (256,256)) for file in glob.glob('/content/mydrive/MyDrive/*.png')]
images = np.asarray(images)
labls = np.ones(images.shape) ## here all labeles are set to ones, just to test the code.
def apply_filter(img):
filters = []
ksize = 31
for theta in np.arange(0, np.pi, np.pi/16):
kern = cv2.getGaborKernel((ksize, ksize), 4.0, theta, 10.0, 0.5, 0, ktype=cv2.CV_32F)
kern /= 1.5*kern.sum()
filters.append(kern)
accum = np.zeros_like(img)
for kern in filters:
fimg = cv2.filter2D(img, cv2.CV_8UC3, kern)
np.maximum(accum, fimg, accum)
return accum
res1=[]
for ig in images:
res1.append(apply_filter(ig))
res1 = np.asarray(res1)
print(res1.shape)
inpt = Input((256,256,3))
c1 = Conv2D(filters = 3, kernel_size=(1,1),strides = (1,1), padding = 'same')(inpt)
c1 = Lambda(apply_filter(np.float32(c1)))
model = Model(inputs=inpt, outputs=c1)
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(images,labls, epochs=5)
应用过滤器的代码(def apply_filters)独立运行,没有任何错误。但是,当我将该函数作为自定义lambda层调用时,它给出了如下所示的错误。 请帮助我纠正此问题。谢谢
TypeError Traceback (most recent call last)
<ipython-input-26-cb9df2f129a2> in <module>()
5 inpt = Input((256,256,3))
6 c1 = Conv2D(filters = 3, kernel_size=(1,1),strides = (1,1), padding = 'same')(inpt)
----> 7 c1 = Lambda(apply_filter(np.float32(c1)))
8 model = Model(inputs=inpt, outputs=c1)
9 model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
TypeError: __array__() takes 1 positional argument but 2 were given