How to convert a image dimensions which are directed through model.flow_from_directory?












0














I am trying to build an image classifier using Keras 2.2.0 and tensorflow 1.9.0



I am getting an error of this sort:



str(data_shape))
ValueError: Error when checking input: expected conv2d_1_input to have shape (1, 224, 224) but got array with shape (224, 224, 3)


Here is the code:



train_datagen=ImageDataGenerator(rotation_range=40,
width_shift_range=0.2,
height_shift_range=0.2,
rescale=1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True,
fill_mode='nearest')

validation_datagen=ImageDataGenerator(rescale=1./255)

train_generator = train_datagen.flow_from_directory('/media/centura/DANISH/mobile backup/moles/train/',class_mode='binary',target_size=(224, 224),batch_size=batch_size)

validation_generator = validation_datagen.flow_from_directory('/media/centura/DANISH/mobile backup/moles/test/',class_mode='binary',target_size=(224, 224),batch_size=batch_size)

#Data Dimensions
img_rows,img_cols=224,224

input_shape1=(1,img_rows,img_cols)

#initialising the model

model=Sequential()

#layer 1
model.add(Conv2D(filters=32, kernel_size=(3,3), strides=(1, 1), padding='same',input_shape=input_shape1,data_format="channels_last"))
model.add(BatchNormalization())
model.add(Activation('relu'))
#model.add(AveragePooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))


#fully connected first layer

model.add(Flatten())
model.add(Dense(500,use_bias=False))
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(Dropout(0.25))


#Fully connected final layer
model.add(Dense(1))
model.add(Activation('sigmoid'))

tensorboard=TensorBoard(log_dir='logs/{}'.format(name))


model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])
#model.summary()
model.fit_generator(train_generator,epochs=50,validation_data=validation_generator,callbacks=[tensorboard])


I believe the error is coming from the train_generator. I searched in stack overflow for similar problems. I found certain solutions but it was not working for me. How can I change the dimensions of the image if it is being called from the .flow_from_directory?










share|improve this question





























    0














    I am trying to build an image classifier using Keras 2.2.0 and tensorflow 1.9.0



    I am getting an error of this sort:



    str(data_shape))
    ValueError: Error when checking input: expected conv2d_1_input to have shape (1, 224, 224) but got array with shape (224, 224, 3)


    Here is the code:



    train_datagen=ImageDataGenerator(rotation_range=40,
    width_shift_range=0.2,
    height_shift_range=0.2,
    rescale=1./255,
    shear_range=0.2,
    zoom_range=0.2,
    horizontal_flip=True,
    fill_mode='nearest')

    validation_datagen=ImageDataGenerator(rescale=1./255)

    train_generator = train_datagen.flow_from_directory('/media/centura/DANISH/mobile backup/moles/train/',class_mode='binary',target_size=(224, 224),batch_size=batch_size)

    validation_generator = validation_datagen.flow_from_directory('/media/centura/DANISH/mobile backup/moles/test/',class_mode='binary',target_size=(224, 224),batch_size=batch_size)

    #Data Dimensions
    img_rows,img_cols=224,224

    input_shape1=(1,img_rows,img_cols)

    #initialising the model

    model=Sequential()

    #layer 1
    model.add(Conv2D(filters=32, kernel_size=(3,3), strides=(1, 1), padding='same',input_shape=input_shape1,data_format="channels_last"))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    #model.add(AveragePooling2D(pool_size=(2,2)))
    model.add(Dropout(0.25))


    #fully connected first layer

    model.add(Flatten())
    model.add(Dense(500,use_bias=False))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(Dropout(0.25))


    #Fully connected final layer
    model.add(Dense(1))
    model.add(Activation('sigmoid'))

    tensorboard=TensorBoard(log_dir='logs/{}'.format(name))


    model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])
    #model.summary()
    model.fit_generator(train_generator,epochs=50,validation_data=validation_generator,callbacks=[tensorboard])


    I believe the error is coming from the train_generator. I searched in stack overflow for similar problems. I found certain solutions but it was not working for me. How can I change the dimensions of the image if it is being called from the .flow_from_directory?










    share|improve this question



























      0












      0








      0







      I am trying to build an image classifier using Keras 2.2.0 and tensorflow 1.9.0



      I am getting an error of this sort:



      str(data_shape))
      ValueError: Error when checking input: expected conv2d_1_input to have shape (1, 224, 224) but got array with shape (224, 224, 3)


      Here is the code:



      train_datagen=ImageDataGenerator(rotation_range=40,
      width_shift_range=0.2,
      height_shift_range=0.2,
      rescale=1./255,
      shear_range=0.2,
      zoom_range=0.2,
      horizontal_flip=True,
      fill_mode='nearest')

      validation_datagen=ImageDataGenerator(rescale=1./255)

      train_generator = train_datagen.flow_from_directory('/media/centura/DANISH/mobile backup/moles/train/',class_mode='binary',target_size=(224, 224),batch_size=batch_size)

      validation_generator = validation_datagen.flow_from_directory('/media/centura/DANISH/mobile backup/moles/test/',class_mode='binary',target_size=(224, 224),batch_size=batch_size)

      #Data Dimensions
      img_rows,img_cols=224,224

      input_shape1=(1,img_rows,img_cols)

      #initialising the model

      model=Sequential()

      #layer 1
      model.add(Conv2D(filters=32, kernel_size=(3,3), strides=(1, 1), padding='same',input_shape=input_shape1,data_format="channels_last"))
      model.add(BatchNormalization())
      model.add(Activation('relu'))
      #model.add(AveragePooling2D(pool_size=(2,2)))
      model.add(Dropout(0.25))


      #fully connected first layer

      model.add(Flatten())
      model.add(Dense(500,use_bias=False))
      model.add(BatchNormalization())
      model.add(Activation('relu'))
      model.add(Dropout(0.25))


      #Fully connected final layer
      model.add(Dense(1))
      model.add(Activation('sigmoid'))

      tensorboard=TensorBoard(log_dir='logs/{}'.format(name))


      model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])
      #model.summary()
      model.fit_generator(train_generator,epochs=50,validation_data=validation_generator,callbacks=[tensorboard])


      I believe the error is coming from the train_generator. I searched in stack overflow for similar problems. I found certain solutions but it was not working for me. How can I change the dimensions of the image if it is being called from the .flow_from_directory?










      share|improve this question















      I am trying to build an image classifier using Keras 2.2.0 and tensorflow 1.9.0



      I am getting an error of this sort:



      str(data_shape))
      ValueError: Error when checking input: expected conv2d_1_input to have shape (1, 224, 224) but got array with shape (224, 224, 3)


      Here is the code:



      train_datagen=ImageDataGenerator(rotation_range=40,
      width_shift_range=0.2,
      height_shift_range=0.2,
      rescale=1./255,
      shear_range=0.2,
      zoom_range=0.2,
      horizontal_flip=True,
      fill_mode='nearest')

      validation_datagen=ImageDataGenerator(rescale=1./255)

      train_generator = train_datagen.flow_from_directory('/media/centura/DANISH/mobile backup/moles/train/',class_mode='binary',target_size=(224, 224),batch_size=batch_size)

      validation_generator = validation_datagen.flow_from_directory('/media/centura/DANISH/mobile backup/moles/test/',class_mode='binary',target_size=(224, 224),batch_size=batch_size)

      #Data Dimensions
      img_rows,img_cols=224,224

      input_shape1=(1,img_rows,img_cols)

      #initialising the model

      model=Sequential()

      #layer 1
      model.add(Conv2D(filters=32, kernel_size=(3,3), strides=(1, 1), padding='same',input_shape=input_shape1,data_format="channels_last"))
      model.add(BatchNormalization())
      model.add(Activation('relu'))
      #model.add(AveragePooling2D(pool_size=(2,2)))
      model.add(Dropout(0.25))


      #fully connected first layer

      model.add(Flatten())
      model.add(Dense(500,use_bias=False))
      model.add(BatchNormalization())
      model.add(Activation('relu'))
      model.add(Dropout(0.25))


      #Fully connected final layer
      model.add(Dense(1))
      model.add(Activation('sigmoid'))

      tensorboard=TensorBoard(log_dir='logs/{}'.format(name))


      model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])
      #model.summary()
      model.fit_generator(train_generator,epochs=50,validation_data=validation_generator,callbacks=[tensorboard])


      I believe the error is coming from the train_generator. I searched in stack overflow for similar problems. I found certain solutions but it was not working for me. How can I change the dimensions of the image if it is being called from the .flow_from_directory?







      python image-processing machine-learning keras conv-neural-network






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 23 '18 at 11:43









      today

      10.2k21536




      10.2k21536










      asked Nov 23 '18 at 9:50









      user10573543

      267




      267
























          1 Answer
          1






          active

          oldest

          votes


















          0














          Let's break down the error step-by-step to find out what it is telling us:




          Error when checking input:




          So it is related to the input data and input layer of the model.




          expected conv2d_1_input to have shape (1, 224, 224)




          If we look at the code for the first convolution layer we see that:



          Conv2D(..., input_shape=input_shape1, ...)


          And the value of input_shape1 as you have defined it is (1,img_rows,img_cols) which is (1, 224, 224). But:




          but got array with shape (224, 224, 3)




          Which means the images generated by the train_generator have a shape of (224, 224, 3) (which is correct and expected).



          As a result, we see these two shapes, the shape of generated images and the given shape to input_shape argument, must be the same. Therefore, you need to modify the value of input_shape1 as follows:



          input_shape1=(img_rows, img_cols, 3)


          which is exactly what a convolution layer expects as its input shape (i.e. (image_height, image_width, image_channels)).






          share|improve this answer





















          • That was exactly the problem. I was confused of the fact,that the keras is expecting a 4D tensor (batch_size,width,height,channels) so i gave it like that.Thank you !
            – user10573543
            Nov 23 '18 at 13:19











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53444241%2fhow-to-convert-a-image-dimensions-which-are-directed-through-model-flow-from-dir%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          Let's break down the error step-by-step to find out what it is telling us:




          Error when checking input:




          So it is related to the input data and input layer of the model.




          expected conv2d_1_input to have shape (1, 224, 224)




          If we look at the code for the first convolution layer we see that:



          Conv2D(..., input_shape=input_shape1, ...)


          And the value of input_shape1 as you have defined it is (1,img_rows,img_cols) which is (1, 224, 224). But:




          but got array with shape (224, 224, 3)




          Which means the images generated by the train_generator have a shape of (224, 224, 3) (which is correct and expected).



          As a result, we see these two shapes, the shape of generated images and the given shape to input_shape argument, must be the same. Therefore, you need to modify the value of input_shape1 as follows:



          input_shape1=(img_rows, img_cols, 3)


          which is exactly what a convolution layer expects as its input shape (i.e. (image_height, image_width, image_channels)).






          share|improve this answer





















          • That was exactly the problem. I was confused of the fact,that the keras is expecting a 4D tensor (batch_size,width,height,channels) so i gave it like that.Thank you !
            – user10573543
            Nov 23 '18 at 13:19
















          0














          Let's break down the error step-by-step to find out what it is telling us:




          Error when checking input:




          So it is related to the input data and input layer of the model.




          expected conv2d_1_input to have shape (1, 224, 224)




          If we look at the code for the first convolution layer we see that:



          Conv2D(..., input_shape=input_shape1, ...)


          And the value of input_shape1 as you have defined it is (1,img_rows,img_cols) which is (1, 224, 224). But:




          but got array with shape (224, 224, 3)




          Which means the images generated by the train_generator have a shape of (224, 224, 3) (which is correct and expected).



          As a result, we see these two shapes, the shape of generated images and the given shape to input_shape argument, must be the same. Therefore, you need to modify the value of input_shape1 as follows:



          input_shape1=(img_rows, img_cols, 3)


          which is exactly what a convolution layer expects as its input shape (i.e. (image_height, image_width, image_channels)).






          share|improve this answer





















          • That was exactly the problem. I was confused of the fact,that the keras is expecting a 4D tensor (batch_size,width,height,channels) so i gave it like that.Thank you !
            – user10573543
            Nov 23 '18 at 13:19














          0












          0








          0






          Let's break down the error step-by-step to find out what it is telling us:




          Error when checking input:




          So it is related to the input data and input layer of the model.




          expected conv2d_1_input to have shape (1, 224, 224)




          If we look at the code for the first convolution layer we see that:



          Conv2D(..., input_shape=input_shape1, ...)


          And the value of input_shape1 as you have defined it is (1,img_rows,img_cols) which is (1, 224, 224). But:




          but got array with shape (224, 224, 3)




          Which means the images generated by the train_generator have a shape of (224, 224, 3) (which is correct and expected).



          As a result, we see these two shapes, the shape of generated images and the given shape to input_shape argument, must be the same. Therefore, you need to modify the value of input_shape1 as follows:



          input_shape1=(img_rows, img_cols, 3)


          which is exactly what a convolution layer expects as its input shape (i.e. (image_height, image_width, image_channels)).






          share|improve this answer












          Let's break down the error step-by-step to find out what it is telling us:




          Error when checking input:




          So it is related to the input data and input layer of the model.




          expected conv2d_1_input to have shape (1, 224, 224)




          If we look at the code for the first convolution layer we see that:



          Conv2D(..., input_shape=input_shape1, ...)


          And the value of input_shape1 as you have defined it is (1,img_rows,img_cols) which is (1, 224, 224). But:




          but got array with shape (224, 224, 3)




          Which means the images generated by the train_generator have a shape of (224, 224, 3) (which is correct and expected).



          As a result, we see these two shapes, the shape of generated images and the given shape to input_shape argument, must be the same. Therefore, you need to modify the value of input_shape1 as follows:



          input_shape1=(img_rows, img_cols, 3)


          which is exactly what a convolution layer expects as its input shape (i.e. (image_height, image_width, image_channels)).







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 23 '18 at 11:40









          today

          10.2k21536




          10.2k21536












          • That was exactly the problem. I was confused of the fact,that the keras is expecting a 4D tensor (batch_size,width,height,channels) so i gave it like that.Thank you !
            – user10573543
            Nov 23 '18 at 13:19


















          • That was exactly the problem. I was confused of the fact,that the keras is expecting a 4D tensor (batch_size,width,height,channels) so i gave it like that.Thank you !
            – user10573543
            Nov 23 '18 at 13:19
















          That was exactly the problem. I was confused of the fact,that the keras is expecting a 4D tensor (batch_size,width,height,channels) so i gave it like that.Thank you !
          – user10573543
          Nov 23 '18 at 13:19




          That was exactly the problem. I was confused of the fact,that the keras is expecting a 4D tensor (batch_size,width,height,channels) so i gave it like that.Thank you !
          – user10573543
          Nov 23 '18 at 13:19


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53444241%2fhow-to-convert-a-image-dimensions-which-are-directed-through-model-flow-from-dir%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          What visual should I use to simply compare current year value vs last year in Power BI desktop

          How to ignore python UserWarning in pytest?

          Alexandru Averescu