In [14]:
import matplotlib.pyplot as plt
%matplotlib inline
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import MaxPooling2D, Input, UpSampling2D
from keras.layers.convolutional import Convolution2D as Conv2D
from keras import backend as K
import cv2

In [2]:
def imshow(img):
    plt.imshow(cv2.cvtColor(img,cv2.COLOR_GRAY2RGB))

In [11]:
img_src=cv2.imread('test_img.bmp')
img_src=cv2.cvtColor(img_src,cv2.COLOR_BGR2RGB)
plt.imshow(img_src)


Out[11]:
<matplotlib.image.AxesImage at 0x22307138588>

In [ ]:
img_src=cv2.cvtColor(img_src,cv2.COLOR_BGR2RGB)

In [8]:
x,y=640,480
img_zip=cv2.resize(img_src,(x,y))

In [17]:
input_img = Input(shape=(x, y, 1))  # adapt this if using `channels_first` image data format

x = Conv2D(16, 3, 3, activation='relu')(input_img)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(8, 3, 3, activation='relu')(x)
x = MaxPooling2D((2, 2))(x)
x = Conv2D(8, 3, 3, activation='relu')(x)
encoded = MaxPooling2D((2, 2))(x)

# at this point the representation is (4, 4, 8) i.e. 128-dimensional

x = Conv2D(8, (3, 3), activation='relu', padding='same')(encoded)
x = UpSampling2D((2, 2))(x)
x = Conv2D(8, (3, 3), activation='relu', padding='same')(x)
x = UpSampling2D((2, 2))(x)
x = Conv2D(16, (3, 3), activation='relu')(x)
x = UpSampling2D((2, 2))(x)
decoded = Conv2D(1, (3, 3), activation='sigmoid', padding='same')(x)

autoencoder = Model(input_img, decoded)
autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')


---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
C:\Anaconda3\lib\site-packages\tensorflow\python\framework\common_shapes.py in _call_cpp_shape_fn_impl(op, input_tensors_needed, input_tensors_as_shapes_needed, debug_python_shape_fn, require_shape_fn)
    669           node_def_str, input_shapes, input_tensors, input_tensors_as_shapes,
--> 670           status)
    671   except errors.InvalidArgumentError as err:

C:\Anaconda3\lib\contextlib.py in __exit__(self, type, value, traceback)
     65             try:
---> 66                 next(self.gen)
     67             except StopIteration:

C:\Anaconda3\lib\site-packages\tensorflow\python\framework\errors_impl.py in raise_exception_on_not_ok_status()
    468           compat.as_text(pywrap_tensorflow.TF_Message(status)),
--> 469           pywrap_tensorflow.TF_GetCode(status))
    470   finally:

InvalidArgumentError: Negative dimension size caused by subtracting 3 from 1 for 'Conv2D_4' (op: 'Conv2D') with input shapes: [?,480,1,640], [3,3,640,16].

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-17-9447719af6a8> in <module>()
      1 input_img = Input(shape=(x, y, 1))  # adapt this if using `channels_first` image data format
      2 
----> 3 x = Conv2D(16, 3, 3, activation='relu')(input_img)
      4 x = MaxPooling2D((2, 2), padding='same')(x)
      5 x = Conv2D(8, 3, 3, activation='relu')(x)

C:\Anaconda3\lib\site-packages\keras\engine\topology.py in __call__(self, x, mask)
    483         if inbound_layers:
    484             # this will call layer.build() if necessary
--> 485             self.add_inbound_node(inbound_layers, node_indices, tensor_indices)
    486             input_added = True
    487 

C:\Anaconda3\lib\site-packages\keras\engine\topology.py in add_inbound_node(self, inbound_layers, node_indices, tensor_indices)
    541         # creating the node automatically updates self.inbound_nodes
    542         # as well as outbound_nodes on inbound layers.
--> 543         Node.create_node(self, inbound_layers, node_indices, tensor_indices)
    544 
    545     def get_output_shape_for(self, input_shape):

C:\Anaconda3\lib\site-packages\keras\engine\topology.py in create_node(cls, outbound_layer, inbound_layers, node_indices, tensor_indices)
    146 
    147         if len(input_tensors) == 1:
--> 148             output_tensors = to_list(outbound_layer.call(input_tensors[0], mask=input_masks[0]))
    149             output_masks = to_list(outbound_layer.compute_mask(input_tensors[0], input_masks[0]))
    150             # TODO: try to auto-infer shape if exception is raised by get_output_shape_for

C:\Anaconda3\lib\site-packages\keras\layers\convolutional.py in call(self, x, mask)
    339                             border_mode=self.border_mode,
    340                             dim_ordering=self.dim_ordering,
--> 341                             filter_shape=self.W_shape)
    342         if self.dim_ordering == 'th':
    343             output = conv_out + K.reshape(self.b, (1, self.nb_filter, 1, 1))

C:\Anaconda3\lib\site-packages\keras\backend\tensorflow_backend.py in conv2d(x, kernel, strides, border_mode, dim_ordering, image_shape, filter_shape)
    934         x = tf.transpose(x, (0, 2, 3, 1))
    935         kernel = tf.transpose(kernel, (2, 3, 1, 0))
--> 936         x = tf.nn.conv2d(x, kernel, strides, padding=padding)
    937         x = tf.transpose(x, (0, 3, 1, 2))
    938     elif dim_ordering == 'tf':

C:\Anaconda3\lib\site-packages\tensorflow\python\ops\gen_nn_ops.py in conv2d(input, filter, strides, padding, use_cudnn_on_gpu, data_format, name)
    394                                 strides=strides, padding=padding,
    395                                 use_cudnn_on_gpu=use_cudnn_on_gpu,
--> 396                                 data_format=data_format, name=name)
    397   return result
    398 

C:\Anaconda3\lib\site-packages\tensorflow\python\framework\op_def_library.py in apply_op(self, op_type_name, name, **keywords)
    761         op = g.create_op(op_type_name, inputs, output_types, name=scope,
    762                          input_types=input_types, attrs=attr_protos,
--> 763                          op_def=op_def)
    764         if output_structure:
    765           outputs = op.outputs

C:\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py in create_op(self, op_type, inputs, dtypes, input_types, name, attrs, op_def, compute_shapes, compute_device)
   2395                     original_op=self._default_original_op, op_def=op_def)
   2396     if compute_shapes:
-> 2397       set_shapes_for_outputs(ret)
   2398     self._add_op(ret)
   2399     self._record_op_seen_by_control_dependencies(ret)

C:\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py in set_shapes_for_outputs(op)
   1755       shape_func = _call_cpp_shape_fn_and_require_op
   1756 
-> 1757   shapes = shape_func(op)
   1758   if shapes is None:
   1759     raise RuntimeError(

C:\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py in call_with_requiring(op)
   1705 
   1706   def call_with_requiring(op):
-> 1707     return call_cpp_shape_fn(op, require_shape_fn=True)
   1708 
   1709   _call_cpp_shape_fn_and_require_op = call_with_requiring

C:\Anaconda3\lib\site-packages\tensorflow\python\framework\common_shapes.py in call_cpp_shape_fn(op, input_tensors_needed, input_tensors_as_shapes_needed, debug_python_shape_fn, require_shape_fn)
    608     res = _call_cpp_shape_fn_impl(op, input_tensors_needed,
    609                                   input_tensors_as_shapes_needed,
--> 610                                   debug_python_shape_fn, require_shape_fn)
    611     if not isinstance(res, dict):
    612       # Handles the case where _call_cpp_shape_fn_impl calls unknown_shape(op).

C:\Anaconda3\lib\site-packages\tensorflow\python\framework\common_shapes.py in _call_cpp_shape_fn_impl(op, input_tensors_needed, input_tensors_as_shapes_needed, debug_python_shape_fn, require_shape_fn)
    673       missing_shape_fn = True
    674     else:
--> 675       raise ValueError(err.message)
    676 
    677   if missing_shape_fn:

ValueError: Negative dimension size caused by subtracting 3 from 1 for 'Conv2D_4' (op: 'Conv2D') with input shapes: [?,480,1,640], [3,3,640,16].

In [ ]:
x_train=

In [ ]:
model.fit(x_train, y_train,
          batch_size=batch_size,
          epochs=epochs,
          verbose=1,
          validation_data=(x_test, y_test))
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])

In [ ]: