Giter VIP home page Giter VIP logo

image-super-resolution's Introduction

Image Super Resolution using in Keras 2+

Implementation of Image Super Resolution CNN in Keras from the paper Image Super-Resolution Using Deep Convolutional Networks.

Also contains models that outperforms the above mentioned model, termed Expanded Super Resolution, Denoiseing Auto Encoder SRCNN which outperforms both of the above models and Deep Denoise SR, which with certain limitations, outperforms all of the above.

Setup

Supports Keras with Theano and Tensorflow backend. Due to recent report that Theano will no longer be updated, Tensorflow is the default backend for this project now.

Requires Pillow, imageio, sklearn, scipy, keras 2.3.1, tensorflow 1.15.0

Usage

Note: The project is going to be reworked. Therefore please refer to Framework-Updates.md to see the changes which will affect performance.

The model weights are already provided in the weights folder, therefore simply running :
python main.py "imgpath", where imgpath is a full path to the image.

The default model is DDSRCNN (dsr), which outperforms the other three models. To switch models,
python main.py "imgpath" --model="type", where type = sr, esr, dsr, ddsr

If the scaling factor needs to be altered then :
python main.py "imgpath" --scale=s, where s can be any number. Default s = 2

If the intermediate step (bilinear scaled image) is needed, then:
python main.py "imgpath" --scale=s --save_intermediate="True"

Window Helper

The windows_helper script contains a C# program for Windows to easily use the Super Resolution script using any of the available models.

Parameters

--model : Can be one of "sr" (Image Super Resolution), "esr" (Expanded SR), "dsr" (Denoiseing Auto Encoder SR), "ddsr" (Deep Denoise SR), "rnsr" (ResNet SR) or "distilled_rnsr" (Distilled ResNet SR)
--scale : Scaling factor can be any integer number. Default is 2x scaling.
--save_intermediate= : Save the intermediate results before applying the Super Resolution algorithm.
--mode : "fast" or "patch". Patch mode can be useful for memory constrained GPU upscaling, whereas fast mode submits whole image for upscaling in one pass.
--suffix : Suffix of the scaled image filename
--patch_size : Used only when patch mode is used. Sets the size of each patch

Model Architecture

Super Resolution CNN (SRCNN)

The model above is the simplest model of the ones described in the paper above, consisting of the 9-1-5 model. Larger architectures can be easily made, but come at the cost of execution time, especially on CPU.

However there are some differences from the original paper:
[1] Used the Adam optimizer instead of RMSProp.
[2] This model contains some 21,000 parameters, more than the 8,400 of the original paper.

It is to be noted that the original models underperform compared to the results posted in the paper. This may be due to the only 91 images being the training set compared to the entire ILSVR 2013 image set. It still performs well, however images are slightly noisy.

Expanded Super Resolution CNN (ESRCNN)

The above is called "Expanded SRCNN", which performs slightly worse than the default SRCNN model on Set5 (PSNR 31.78 dB vs 32.4 dB).

The "Expansion" occurs in the intermediate hidden layer, in which instead of just 1x1 kernels, we also use 3x3 and 5x5 kernels in order to maximize information learned from the layer. The outputs of this layer are then averaged, in order to construct more robust upscaled images.

Denoiseing (Auto Encoder) Super Resolution CNN (DSRCNN)

The above is the "Denoiseing Auto Encoder SRCNN", which performs even better than SRCNN on Set5 (PSNR 32.57 dB vs 32.4 dB).

This model uses bridge connections between the convolutional layers of the same level in order to speed up convergence and improve output results. The bridge connections are averaged to be more robust.

Since the training images are passed through a gausian filter (sigma = 0.5), then downscaled to 1/3rd the size, then upscaled to the original 33x33 size images, the images can be considered "noisy". Thus, this auto encoder quickly improves on the earlier results, and reduces the noisy output image problem faced by the simpler SRCNN model.

Deep Denoiseing Super Resolution (DDSRCNN)

The above is the "Deep Denoiseing SRCNN", which is a modified form of the architecture described in the paper "Image Restoration Using Convolutional Auto-encoders with Symmetric Skip Connections" applied to image super-resolution. It can perform far better than even the Denoiseing SRCNN, but is currently not working properly.

Similar to the paper Image Restoration Using Convolutional Auto-encoders with Symmetric Skip Connections, this can be considered a highly simplified and shallow model compared to the 30 layer architecture used in the above paper.

ResNet Super Resolution (ResNet SR)

The above is the "ResNet SR" model, derived from the "SRResNet" model of the paper [Photo-Realistic Single Image Super-Resolution Using a Generative Adversarial Network](https://arxiv.org/abs/1609.04802)

Currently uses only 6 residual blocks and 2x upscaling rather than the 15 residual blocks and the 4x upscaling from the paper.

Efficient SubPixel Convolutional Neural Network (ESPCNN)

The above model is the Efficient Subpixel Convolution Neural Network which uses the Subpixel Convolution layers to upscale rather than UpSampling or Deconvolution. Currently has not been trained properly.

GAN Image Super Resolution (GANSR)

The above model is the GAN trained Image Super Resolution network based on the ResNet SR and the SRGAN from the paper above.

Note : Does not work properly right now.

Distilled ResNet Super Resolution (Distilled ResNetSR)

The above model is a smaller ResNet SR that was trained using model distilation techniques from the "teacher" model - the original larger ResNet SR (with 6 residual blocks).

The model was trained via the distill_network.py script which can be used to perform distilation training from any teacher network onto a smaller 'student' network.

Non-Local ResNet Super Resolution (Non-Local ResNetSR)

The above model is a trial to see if Non-Local blocks can obtain better super resolution.

Various issues :

  1. They break the fully convolutional behaviour of the network. Due to the flatten and reshape parts of this module, you need to have a set size for the image when building it.

Therefore you cannot construct one model and then pass random size input images to evaluate.

  1. The non local blocks require vast amount of memory as their intermediate products. I think this is the reason they suggested to use this at the end of the network where the spatial dimension is just 14x14 or 7x7.

I had consistent ooms when trying it on multiple positions of a super resolution network, and could only successfully place it at the last ResNet block without oom (on just 4 GB 980M).

Finally, I was able to train a model anyway and it got pretty high psnr scores. I wasn't able to evaluate that, and was able to distill the model into ordinary ResNet. It got exactly same psnr score as the original non local model. Evaluating that, all the images were a little smoothed out. This is worse than a distilled ResNet which obtains a lower psnr score but sharper images.

Training

If you wish to train the network on your own data set, follow these steps (Performance may vary) :
[1] Save all of your input images of any size in the "input_images" folder
[2] Run img_utils.py function, transform_images(input_path, scale_factor). By default, input_path is "input_images" path. Note: Unless you are training ESPCNN, set the variable true_upsampling to False and then run the img_utils.py script to generate the dataset. Only for ESPCNN training do you need to set true_upsampling to True.
[3] Open tests.py and un-comment the lines at model.fit(...), where model can be sr, esr or dsr, ddsr.
Note: It may be useful to save the original weights in some other location.
[4] Execute tests.py to begin training. GPU is recommended, although if small number of images are provided then GPU may not be required.

Caveats

Very large images may not work with the GPU. Therefore,
[1] If using Theano, set device="cpu" and cnmem=0.0 in theanorc.txt
[2] If using Tensorflow, set it to cpu mode

On the CPU, extremely high resolution images of the size upto 6000 x 6000 pixels can be handled if 16 GB RAM is provided.

Examples

There are 14 extra images provided in results, 2 of which (Monarch Butterfly and Zebra) have been scaled using both bilinear, SRCNN, ESRCNN and DSRCNN.

Monarch Butterfly

Bilinear SRCNN
ESRCNN DDSRCNN

Zebra

Bilinear SRCNN
ESRCNN DDSRCNN

image-super-resolution's People

Contributors

captainstabs avatar titu1994 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

image-super-resolution's Issues

validation issue

hello,
i got a quick question here,
from the epochs i have acceptable results although its not as good as what mentioned in the paper, however, i don't know why the val_PSNRLoss at last epoch is 24.xxx and when validating the model it drops to average 13.xxxx
Am i doing something wrong here ? maybe i am confused with the difference between the val psnr loss and the model validating

thanks

Epoch 50/50
24576/24576 [==============================] - 4532s - loss: 0.0042 - PSNRLoss: 26.9141 - val_loss: 0.0055 - val_PSNRLoss: 24.2536
Validating model
Validating images from path
validated image:
126058_255_RGB_part2.tif
13.5239350796
validated image:
126058_255_RGB_part4.tif
13.6472463608
validated image:
126058_255_RGB_part3.tif
14.0380191803
Average PSNR value of validation images is
13.7364002069

Cannot obtain comparable performance

@titu1994
Hi,
First I want to thank you for your great work! It is very inspiring.
Right now, I'm trying the very basic CNN for SR ("BaseSuperResolutionModel") use your code. Basically, what I've done is calling the img_utils.py function (scale = 3) to extract patches and then calling the test.py function.
I'm using the "set 5" dataset as validation set. After 100 epochs, the training PSNR is close to 28.3dB and validation PSNR is close to 27.4dB. The loss did not decrease after 100 epochs.
I left all the other parameters as default.

I noticed you commented that you also got worse performance comparing to that reported in the paper. But 27.4 dB is way worse than the number in the paper (32.6dB).

I'm wondering if you witnessed similar performance as I reported.

Thanks

Layer reshape issue

This is the input code I've Given:

X_array=np.asarray(X_train).astype(np.int)

y_array=np.asarray(y_train).astype(np.int)
X_shaped = np.reshape(X_array, newshape=(-1,18727,3))
y_shaped = np.reshape(y_array,newshape=(-1,18727,2))

model = Sequential()
model.add(LSTM(units=1, input_shape=(10000,3), return_sequences=True))
model.add(LSTMt_shape=(1,18727,3),dropout=0.25,return_sequences=True, input_shape=(-1,18727,2)))

model.add(LSTM(132,batch_input_shape=(1,18727,2),dropout=0.25,return_sequences=True))
model.add(Dense(1,batch_input_shape=(1,18727,3),activation='softmax',batch_size=32))
model.add(Dense(1,batch_input_shape=(1,18727,2),activation='softmax',batch_size=32))

model.compile(loss="mean_absolute_error", optimizer="adam", metrics= ['accuracy'])
model.compile(loss='mse', optimizer='rmsprop',metrics=['accuracy'])## Binary cross entropy/ categorical cross
start = time.time()
print ('compilation time : ', time.time() - start) (units=1, input_shape=(4000,2), return_sequences=True))
model.add(LSTM(132,batch_input)

The Error im getting is this:

Epoch 1/100
WARNING:tensorflow:Model was constructed with shape (None, 10000, 3) for input KerasTensor(type_spec=TensorSpec(shape=(None, 10000, 3), dtype=tf.float32, name='lstm_16_input'), name='lstm_16_input', description="created by layer 'lstm_16_input'"), but it was called on an input with incompatible shape (None, 18727, 3).
WARNING:tensorflow:Model was constructed with shape (None, 10000, 3) for input KerasTensor(type_spec=TensorSpec(shape=(None, 10000, 3), dtype=tf.float32, name='lstm_16_input'), name='lstm_16_input', description="created by layer 'lstm_16_input'"), but it was called on an input with incompatible shape (None, 18727, 3).
1/1 [==============================] - ETA: 0s - loss: 9914.3594 - accuracy: 5.3399e-04

ValueError Traceback (most recent call last)
in ()
6 #y_scaled = scaler.fit_transform(y_shaped)
7 #print(X_scaled,y_scaled)
----> 8 history = model.fit(X_shaped,y_shaped,epochs=100, validation_data=(X_array,y_array))
9 print(model.summary())

10 frames
/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)
975 except Exception as e: # pylint:disable=broad-except
976 if hasattr(e, "ag_error_metadata"):
--> 977 raise e.ag_error_metadata.to_exception(e)
978 else:
979 raise

ValueError: in user code:

/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/training.py:1233 test_function  *
    return step_function(self, iterator)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/training.py:1224 step_function  **
    outputs = model.distribute_strategy.run(run_step, args=(data,))
/usr/local/lib/python3.7/dist-packages/tensorflow/python/distribute/distribute_lib.py:1259 run
    return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/distribute/distribute_lib.py:2730 call_for_each_replica
    return self._call_for_each_replica(fn, args, kwargs)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/distribute/distribute_lib.py:3417 _call_for_each_replica
    return fn(*args, **kwargs)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/training.py:1217 run_step  **
    outputs = model.test_step(data)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/training.py:1183 test_step
    y_pred = self(x, training=False)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/base_layer.py:998 __call__
    input_spec.assert_input_compatibility(self.input_spec, inputs, self.name)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/input_spec.py:223 assert_input_compatibility
    str(tuple(shape)))

ValueError: Input 0 of layer sequential_3 is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: (None, 3)

Train with own dataset

Dear Titu,
Thank you for sharing your source code. I try to train your code with my own dataset which include images with size 128*64. But I get a same error in most of train model in test.py.
error:
ValueError:
Using TensorFlow backend.
Training model : ImageSuperResolutionModel
2018-02-15 09:17:35.000003: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.
2018-02-15 09:17:35.000047: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.
2018-02-15 09:17:35.000061: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
2018-02-15 09:17:35.214561: I tensorflow/core/common_runtime/gpu/gpu_device.cc:887] Found device 0 with properties:
name: GeForce GTX TITAN X
major: 5 minor: 2 memoryClockRate (GHz) 1.076
pciBusID 0000:19:00.0
Total memory: 11.92GiB
Free memory: 3.33GiB
2018-02-15 09:17:35.214608: I tensorflow/core/common_runtime/gpu/gpu_device.cc:908] DMA: 0
2018-02-15 09:17:35.214622: I tensorflow/core/common_runtime/gpu/gpu_device.cc:918] 0: Y
2018-02-15 09:17:35.214644: I tensorflow/core/common_runtime/gpu/gpu_device.cc:977] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX TITAN X, pci bus id: 0000:19:00.0)
Epoch 1/250
Found 51744 images.
Traceback (most recent call last):
File "tests.py", line 47, in
sr.fit(nb_epochs=250)
File "/mnt/home/ramin/srcnn-org-codes/org/Image-Super-Resolution/models.py", line 516, in fit
return super(ImageSuperResolutionModel, self).fit(batch_size, nb_epochs, save_history, history_fn)
File "/mnt/home/ramin/srcnn-org-codes/org/Image-Super-Resolution/models.py", line 122, in fit
validation_steps=val_count // batch_size + 1)
File "/mnt/home/ramin/Image-Super-Resolution/superRe/lib/python3.4/site-packages/keras/legacy/interfaces.py", line 87, in wrapper
return func(*args, **kwargs)
File "/mnt/home/ramin/Image-Super-Resolution/superRe/lib/python3.4/site-packages/keras/engine/training.py", line 2115, in fit_generator
generator_output = next(output_generator)
File "/mnt/home/ramin/Image-Super-Resolution/superRe/lib/python3.4/site-packages/keras/utils/data_utils.py", line 735, in get
six.reraise(value.class, value, value.traceback)
File "/mnt/home/ramin/Image-Super-Resolution/superRe/lib/python3.4/site-packages/six.py", line 693, in reraise
raise value
File "/mnt/home/ramin/Image-Super-Resolution/superRe/lib/python3.4/site-packages/keras/utils/data_utils.py", line 635, in data_generator_task
generator_output = next(self._generator)
File "/mnt/home/ramin/srcnn-org-codes/org/Image-Super-Resolution/img_utils.py", line 303, in image_generator
batch_x[i] = img
ValueError: could not broadcast input array from shape (16,16,3) into shape (64,64,3)
Exception ignored in: <bound method Session.del of <tensorflow.python.client.session.Session object at 0x7fe3e2aa9d68>>
Traceback (most recent call last):
File "/mnt/home/ramin/Image-Super-Resolution/superRe/lib/python3.4/site-packages/tensorflow/python/client/session.py", line 587, in del
TypeError: 'NoneType' object is not callable

I am very appreciate from you, if you help me about it.
Thank you,
Ramin

New Super-Resolution Benchmarks

Hello,

MSU Graphics & Media Lab Video Group has recently launched two new Super-Resolution Benchmarks.

If you are interested in participating, you can add your algorithm following the submission steps:

We would be grateful for your feedback on our work!

Permission denied

hello, i came across the following problem when i tried your code. I tried it in cmd prompt and spyder, and it showed the same error (in windows 7). I have given the folder all permissoin. The following is the error message:

runfile('D:/hdd/work/Image-Super-Resolution-master/main.py', args='"d:/hdd/work/Image-Super-Resolution-master/input_images/"', wdir='D:/hdd/work/Image-Super-Resolution-master')
Reloaded modules: img_utils, models, advanced
Traceback (most recent call last):

File "", line 1, in
runfile('D:/hdd/work/Image-Super-Resolution-master/main.py', args='"d:/hdd/work/Image-Super-Resolution-master/input_images/"', wdir='D:/hdd/work/Image-Super-Resolution-master')

File "D:\hdd\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 866, in runfile
execfile(filename, namespace)

File "D:\hdd\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)

File "D:/hdd/work/Image-Super-Resolution-master/main.py", line 50, in
model.upscale(path, save_intermediate=save, mode=mode, patch_size=patch_size, suffix=suffix)

File "D:\hdd\work\Image-Super-Resolution-master\models.py", line 133, in upscale
true_img = imread(img_path, mode='RGB')

File "D:\hdd\Anaconda3\lib\site-packages\scipy\misc\pilutil.py", line 154, in imread
im = Image.open(name)

File "D:\hdd\Anaconda3\lib\site-packages\PIL\Image.py", line 2280, in open
fp = builtins.open(filename, "rb")

PermissionError: [Errno 13] Permission denied: 'd:/hdd/work/Image-Super-Resolution-master/input_images/'

I hope you can give me some solutions!

Inclusion of other techniques

Requirements

Hi is there any doc on requirements? I'm running tensor flow with keras and I get errors on both python 2.7 and python 3.5.

Any help would be appreciated, thank you!

ImportError: cannot import name '__check_build'

Hi @titu1994
thank you for your great work in the progect, especially Supports Keras with Tensorflow backend, i failed to try your work befor because i never get Theano backend work in windows.
now when i try to upscal my own photo unfortunately i get this error.

python main.py G:\titu1994 Image-Super-Resolution\bank_lr.png
Using TensorFlow backend.
Traceback (most recent call last):
File "main.py", line 1, in
import models
File "G:\idm\titu1994 Image-Super-Resolution-master\models.py", line 12, in
import img_utils
File "G:\idm\titu1994 Image-Super-Resolution-master\img_utils.py", line 5, in
from sklearn.feature_extraction.image import reconstruct_from_patches_2d, extract_patches_2d
File "C:\Users\ABDO\AppData\Local\Programs\Python\Python35\lib\site-packages\sklearn_init_.py", line 133, in
from . import __check_build
ImportError: cannot import name '__check_build'
how can i solve this please.

module 'img_utils' has no attribute 'output_path'

I ran the following command line: python main.py D:\3rd_semester\low_res_img_test.jpg --model=dsr
I already installed the module img_utils
However, it appeared an error said 'output_path' not found. Search on the internet and there's not solution.
Looking for help.
Thanks!

ValueError: input shapes: [9,9,3,64], [9,9,64,3].

$ python main.py "input2.jpg" --scale=2 --model="sr"

Using TensorFlow backend.
Old Size : (445, 676, 3)
New Size : (890, 1352, 3)
Number of patches = 1187635, Patch Shape = (8, 8)
Saving intermediate image.
tensorflow.python.framework.errors_impl.InvalidArgumentError: Dimension 2 in both shapes must be equal, but are 3 and 64 for 'Assign' (op: 'Assign') with input shapes: [9,9,3,64], [9,9,64,3].

ValueError: could not broadcast input array from shape (32,32,3) into shape (64,64,3)

Hello there, I also encountered this problem.
Traceback (most recent call last):
File "tests.py", line 47, in
sr.fit(nb_epochs=250)
File "/home/tensor/Checuk/Image-Super-Resolution/models.py", line 516, in fit
return super(ImageSuperResolutionModel, self).fit(batch_size, nb_epochs, save_history, history_fn)
File "/home/tensor/Cheuk/Image-Super-Resolution/models.py", line 122, in fit
validation_steps=val_count // batch_size + 1)
File "/usr/local/lib/python3.5/dist-packages/keras/legacy/interfaces.py", line 91, in wrapper
return func(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/keras/engine/training.py", line 2194, in fit_generator
generator_output = next(output_generator)
File "/usr/local/lib/python3.5/dist-packages/keras/utils/data_utils.py", line 793, in get
six.reraise(value.class, value, value.traceback)
File "/usr/local/lib/python3.5/dist-packages/six.py", line 693, in reraise
raise value
File "/usr/local/lib/python3.5/dist-packages/keras/utils/data_utils.py", line 658, in _data_generator_task
generator_output = next(self._generator)
File "/home/tensor/Cheuk/Image-Super-Resolution/img_utils.py", line 301, in image_generator
batch_x[i] = img
ValueError: could not broadcast input array from shape (32,32,3) into shape (64,64,3)

I tried to change the def create_model, but it didn't help, and I also tried to change the parameters of the img_utils.
If you have time, please help me fix this problem. Thanks.

ValueError: Only tensors of same shape can be merged by layeradd_1 Got input shapes: [(None, 64, 8, 8), (None, 64, 8, 64)]

sr and esr are working fine. But when I ran python main.py "input_images/tt26.bmp" --model=dsr --save_intermediate=True , I am getting following error :
Traceback (most recent call last):
File "main.py", line 50, in
model.upscale(path, save_intermediate=save, mode=mode, patch_size=patch_size, suffix=suffix)
File "/home/ankurk/ML/Image Super Resolution/Image-Super-Resolution-master/models.py", line 182, in upscale
model = self.create_model(img_height, img_width, load_weights=True)
File "/home/ankurk/ML/Image Super Resolution/Image-Super-Resolution-master/models.py", line 565, in create_model
level2 = Add()([level2_1, level2_2])
File "/home/ankurk/anaconda3/lib/python3.5/site-packages/keras/engine/topology.py", line 530, in call
self.build(input_shapes)
File "/home/ankurk/anaconda3/lib/python3.5/site-packages/keras/layers/merge.py", line 39, in build
' Got input shapes: %s' % input_shape)
ValueError: Only tensors of same shape can be merged by layeradd_1 Got input shapes: [(None, 64, 8, 8), (None, 64, 8, 64)]

Res-net do not work!!

Hi. I was very impressed with your code.
It was very helpful.

But the Res-Net part does not work when trainning .
The following error message is displayed.

ValueError: CudaNdarray_inplace_elemwise need same dimensions (or broadcastable dimension)
Apply node that caused the error: GpuIncSubtensor{Inc;::, ::, int64::int64, int64::int64}(GpuAlloc{memset_0=True}.0, GpuSubtensor{::, int64::int64, ::, ::}.0, Constant{0}, Constant{2}, Constant{0}, Constant{2})
Toposort index: 1085
Inputs types: [CudaNdarrayType(float32, 4D), CudaNdarrayType(float32, 4D), Scalar(int64), Scalar(int64), Scalar(int64), Scalar(int64)]
Inputs shapes: [(128, 64, 16, 512), (128, 2, 8, 256), (), (), (), ()]
Inputs strides: [(524288, 8192, 512, 1), (16384, 8192, 256, 1), (), (), (), ()]
Inputs values: ['not shown', 'not shown', 0, 2, 0, 2]
Outputs clients: [[GpuIncSubtensor{Inc;::, ::, int64::int64, int64::int64}(GpuIncSubtensor{Inc;::, ::, int64::int64, int64::int64}.0, GpuSubtensor{::, int64::int64, ::, ::}.0, Constant{0}, Constant{2}, Constant{1}, Constant{2})]]

Is it due to insufficient memory?
I don't understand that....

p.s I have also changed "nb_residual = 14" to 3

how to train the SR model for scale 4

I have met some questions when i want to train a model for scale = 4, the following are what i did
Firstly , i ran the image_utils.py , i changed the scaling_factor from 2 to 4 and changed the trup_upscale form False to True, then i got the train images in the floder.
Then ,i ran the three lines in test.py:
if name == "main":
path = r""
val_path = "val_images/"
scale = 4
sr = models.ImageSuperResolutionModel(scale)
sr.create_model()
sr.fit(nb_epochs=250)
however i met the errors :
Using Theano backend.
Training model : ImageSuperResolutionModel
Epoch 1/250
Found 23552 images.
Exception in thread Thread-1:
Traceback (most recent call last):
File "/home/software/local/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/home/software/local/lib/python2.7/threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "/home/software/local/lib/python2.7/site-packages/keras/engine/training.py", line 425, in data_generator_task
generator_output = next(generator)
File "/local/home/share/xujinchang/download/Image-Super-Resolution-master/img_utils.py", line 216, in image_generator
batch_x[i] = img.transpose((2, 0, 1))
ValueError: could not broadcast input array from shape (3,16,16) into shape (3,64,64)

Traceback (most recent call last):
File "train_sr.py", line 11, in
sr.fit(nb_epochs=250)
File "/local/home/share/xujinchang/download/Image-Super-Resolution-master/models.py", line 487, in fit
return super(ImageSuperResolutionModel, self).fit(batch_size, nb_epochs, save_history, history_fn)
File "/local/home/share/xujinchang/download/Image-Super-Resolution-master/models.py", line 100, in fit
nb_val_samples=val_count)
File "/home/software/local/lib/python2.7/site-packages/keras/engine/training.py", line 1417, in fit_generator
'or (x, y). Found: ' + str(generator_output))
Exception: output of generator should be a tuple (x, y, sample_weight) or (x, y). Found: None
by the way, i didn't do anything in model.py.
Next I changed the models.py class BaseSuperResolutionModel(object) :
self.type_true_upscaling = True
it happened the different errors like these:
Using Theano backend.

Training model : ImageSuperResolutionModel
Epoch 1/250
Found 23552 images.
Traceback (most recent call last):
File "train_sr.py", line 11, in
sr.fit(nb_epochs=250)
File "/local/home/share/xujinchang/download/Image-Super-Resolution-master/models.py", line 487, in fit
return super(ImageSuperResolutionModel, self).fit(batch_size, nb_epochs, save_history, history_fn)
File "/local/home/share/xujinchang/download/Image-Super-Resolution-master/models.py", line 100, in fit
nb_val_samples=val_count)
File "/home/software/local/lib/python2.7/site-packages/keras/engine/training.py", line 1443, in fit_generator
class_weight=class_weight)
File "/home/software/local/lib/python2.7/site-packages/keras/engine/training.py", line 1215, in train_on_batch
check_batch_dim=True)
File "/home/software/local/lib/python2.7/site-packages/keras/engine/training.py", line 961, in _standardize_user_data
exception_prefix='model input')
File "/home/software/local/lib/python2.7/site-packages/keras/engine/training.py", line 108, in standardize_input_data
str(array.shape))
Exception: Error when checking model input: expected input_1 to have shape (None, 3, 32, 32) but got array with shape (128, 3, 16, 16)

I would appreciate it if you can help me with these problems.

Problem with PSNRLoss

Hi,
When I tried to run an example, I got the following error in PSNRLoss :
AttributeError: 'Tensor' object has no attribute 'log10'

I am using :

  • Python 3.6.0
  • Tensorflow 0.12.1
  • Theano 0.9.0dev5.dev-e345e095f94b0186b401977607eb009612ac821f
  • Keras 1.2.0 with tensorflow backend

Any ideas ?

Not able to run with GPU, CUDNN_INTERNAL_STATUS_ERROR

Hi,

I am very impressed by your work and i appreciate it.
Your code run with cpu but I am not able to get it working with gpu

I am using theano as backend as mentioned. I have cuda configured properly as I am able to run other gpu based models of mine.

But when i run your code with GPU i get the following error, can u get me out of this, I am looking forward to train your models on my own dataset.

python main.py --model=sr --mode=fast
Using Theano backend.
Using cuDNN version 5110 on context None
Mapped name None to device cuda: GeForce GT 710 (0000:01:00.0)
Old Size : (1000, 1000, 3)
New Size : (2000, 2000, 3)
Image is reshaped to : (2000, 2000, 3)
th
Model loaded.
Traceback (most recent call last):
File "/home/avinash/.virtualenvs/cv/local/lib/python3.5/site-packages/theano/compile/function_module.py", line 884, in call
self.fn() if output_subset is None else
RuntimeError: error doing operation: CUDNN_STATUS_INTERNAL_ERROR

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "main.py", line 62, in
model.upscale(path, save_intermediate=save, mode=mode, patch_size=patch_size, suffix=suffix)
File "/home/avinash/ml/Image-Super-Resolution/models.py", line 190, in upscale
result = model.predict(img_conv, batch_size=128, verbose=verbose)
File "/home/avinash/.virtualenvs/cv/local/lib/python3.5/site-packages/keras/engine/training.py", line 1591, in predict
batch_size=batch_size, verbose=verbose)
File "/home/avinash/.virtualenvs/cv/local/lib/python3.5/site-packages/keras/engine/training.py", line 1218, in _predict_loop
batch_outs = f(ins_batch)
File "/home/avinash/.virtualenvs/cv/local/lib/python3.5/site-packages/keras/backend/theano_backend.py", line 1196, in call
return self.function(*inputs)
File "/home/avinash/.virtualenvs/cv/local/lib/python3.5/site-packages/theano/compile/function_module.py", line 898, in call
storage_map=getattr(self.fn, 'storage_map', None))
File "/home/avinash/.virtualenvs/cv/local/lib/python3.5/site-packages/theano/gof/link.py", line 325, in raise_with_op
reraise(exc_type, exc_value, exc_trace)
File "/home/avinash/.virtualenvs/cv/local/lib/python3.5/site-packages/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/home/avinash/.virtualenvs/cv/local/lib/python3.5/site-packages/theano/compile/function_module.py", line 884, in call
self.fn() if output_subset is None else
RuntimeError: error doing operation: CUDNN_STATUS_INTERNAL_ERROR
Apply node that caused the error: GpuDnnConv{algo='small', inplace=True}(GpuContiguous.0, GpuContiguous.0, GpuAllocEmpty{dtype='float32', context_name=None}.0, GpuDnnConvDesc{border_mode='half', subsample=(1, 1), dilation=(1, 1), conv_mode='conv', precision='float32'}.0, Constant{1.0}, Constant{0.0})
Toposort index: 36
Inputs types: [GpuArrayType(float32, 4D), GpuArrayType(float32, 4D), GpuArrayType(float32, 4D), <theano.gof.type.CDataType object at 0x7f448b27ef60>, Scalar(float32), Scalar(float32)]
Inputs shapes: [(1, 3, 2000, 2000), (64, 3, 9, 9), (1, 64, 2000, 2000), 'No shapes', (), ()]
Inputs strides: [(48000000, 16000000, 8000, 4), (972, 324, 36, 4), (1024000000, 16000000, 8000, 4), 'No strides', (), ()]
Inputs values: ['not shown', 'not shown', 'not shown', <capsule object NULL at 0x7f448793c450>, 1.0, 0.0]
Outputs clients: [[GpuElemwise{Composite{(i0 * ((i1 + i2) + Abs((i1 + i2))))}}[(0, 1)](GpuArrayConstant{[[[[ 0.5]]]]}, GpuDnnConv{algo='small', inplace=True}.0, InplaceGpuDimShuffle{x,0,x,x}.0)]]

HINT: Re-running with most Theano optimization disabled could give you a back-trace of when this node was created. This can be done with by setting the Theano flag 'optimizer=fast_compile'. If that does not work, Theano optimizations can be disabled with 'optimizer=None'.
HINT: Use the Theano flag 'exception_verbosity=high' for a debugprint and storage map footprint of this apply node.
*** Error in `python': free(): invalid pointer: 0x00007f44b7fca060 ***
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x777e5)[0x7f44e70997e5]
/lib/x86_64-linux-gnu/libc.so.6(+0x7fe0a)[0x7f44e70a1e0a]
/lib/x86_64-linux-gnu/libc.so.6(cfree+0x4c)[0x7f44e70a598c]
/usr/local/cuda-8.0/lib64/libcudnn.so.5(+0x3bb291)[0x7f44c6a1c291]
/usr/local/cuda-8.0/lib64/libcudnn.so.5(cudnnDestroy+0x118)[0x7f44c669e4a8]
python[0x49163e]
python[0x587b71]
/home/avinash/.virtualenvs/cv/local/lib/python3.5/site-packages/pygpu-0.6.5-py3.5-linux-x86_64.egg/pygpu/gpuarray.cpython-35m-x86_64-linux-gnu.so(+0xb43e)[0x7f44cd2d243e]
python[0x515e1d]
python(_PyGC_CollectNoFail+0x27)[0x605327]
python(PyImport_Cleanup+0x354)[0x51b0a4]
python(Py_Finalize+0x5e)[0x5fea5e]
python(Py_Main+0x644)[0x63e9c4]
python(main+0xe1)[0x4cfe41]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0)[0x7f44e7042830]
python(_start+0x29)[0x5d5f29]
======= Memory map: ========
00400000-007a8000 r-xp 00000000 08:03 4202316 /home/avinash/.virtualenvs/cv/bin/python3
009a8000-009aa000 r--p 003a8000 08:03 4202316 /home/avinash/.virtualenvs/cv/bin/python3
009aa000-00a41000 rw-p 003aa000 08:03 4202316 /home/avinash/.virtualenvs/cv/bin/python3

Issue while training the Network

Good evening, i'm trying to train and test the CNN following the steps you mention in the readme file.
I tried using some samples of mine, but i got some error. So i tried training the network using the dataset in your github. (i didn't modify anything in input_images or in validation images because i was just trying to understand how you trained the network).
I keep getting this error:

errore1

Can you please help me solving this error? I don't know where to start.
Thanks in advance

error when run the example codes

Thanks for your code. When I train the simple 'Super Resolution' model as you suggested, a error came out:

Exception: Error when checking model target: expected output to have shape (None, 3, 33, 3) but got array with shape (35200, 3, 33, 33)

The line resulted in this error is:

self.model.fit(trainX, trainY, batch_size=batch_size, nb_epoch=nb_epochs, callbacks=callback_list, validation_data=(testX, testY))

could you help me on this? Thanks

SyntaxError: invalid syntax in models.py

Hi Titu,

I got an error when first downloading and runing the main.py, the error is below, where do I miss to setup?

Thanks!
Jianbin


Traceback (most recent call last):
File "main.py", line 1, in
import models
File "/home/jianmin/DL/Super_resolution/Image-Super-Resolution/models.py", line 70
def create_model(self, height=32, width=32, channels=3, load_weights=False, batch_size=128) -> Model:
^
SyntaxError: invalid syntax

ValueError: Dimension 2 in both shapes must be equal, but are 3 and 64 for 'Assign' (op: 'Assign') with input shapes: [3,3,3,64], [3,3,64,3].

i got this error while doing the testing,

Traceback (most recent call last):
File "main.py", line 57, in
model.upscale(p, save_intermediate=save, mode=mode, patch_size=patch_size, suffix=suffix)
File "C:\Users\Administrator\Desktop\Image-Super-Resolution-master\models.py", line 202, in upscale
model = self.create_model(img_dim_2, img_dim_1, load_weights=True)
File "C:\Users\Administrator\Desktop\Image-Super-Resolution-master\models.py", line 601, in create_model
if load_weights: model.load_weights(self.weight_path)
File "E:\Anaconda3\lib\site-packages\keras\engine\topology.py", line 2656, in load_weights
f, self.layers, reshape=reshape)
File "E:\Anaconda3\lib\site-packages\keras\engine\topology.py", line 3382, in load_weights_from_hdf5_group
K.batch_set_value(weight_value_tuples)
File "E:\Anaconda3\lib\site-packages\keras\backend\tensorflow_backend.py", line 2368, in batch_set_value
assign_op = x.assign(assign_placeholder)
File "E:\Anaconda3\lib\site-packages\tensorflow\python\ops\variables.py", line 516, in assign
return state_ops.assign(self._variable, value, use_locking=use_locking)
File "E:\Anaconda3\lib\site-packages\tensorflow\python\ops\state_ops.py", line 271, in assign
validate_shape=validate_shape)
File "E:\Anaconda3\lib\site-packages\tensorflow\python\ops\gen_state_ops.py", line 45, in assign
use_locking=use_locking, name=name)
File "E:\Anaconda3\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 767, in apply_op
op_def=op_def)
File "E:\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 2508, in create_op
set_shapes_for_outputs(ret)
File "E:\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 1873, in set_shapes_for_outputs
shapes = shape_func(op)
File "E:\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 1823, in call_with_requiring
return call_cpp_shape_fn(op, require_shape_fn=True)
File "E:\Anaconda3\lib\site-packages\tensorflow\python\framework\common_shapes.py", line 610, in call_cpp_shape_fn
debug_python_shape_fn, require_shape_fn)
File "E:\Anaconda3\lib\site-packages\tensorflow\python\framework\common_shapes.py", line 676, in _call_cpp_shape_fn_impl
raise ValueError(err.message)
ValueError: Dimension 2 in both shapes must be equal, but are 3 and 64 for 'Assign' (op: 'Assign') with input shapes: [3,3,3,64], [3,3,64,3].

->Model syntax error

Traceback (most recent call last):
File "drive/PythonOrtam/SuperResolution/main.py", line 1, in
import models
File "/content/drive/PythonOrtam/SuperResolution/models.py", line 70
def create_model(self, height=32, width=32, channels=3, load_weights=False, batch_size=128) -> Model:
^
SyntaxError: invalid syntax

Traceback (most recent call last):
File "drive/PythonOrtam/SuperResolution/main.py", line 1, in
import models
File "/content/drive/PythonOrtam/SuperResolution/models.py", line 277
def _evaluate(sr_model: BaseSuperResolutionModel, validation_dir, scale_pred=False):
^
SyntaxError: invalid syntax

I have some errors. Can you help me please?

Input dimension mis-match. (input[1].shape[1] = 3, input[2].shape[1] = 64)

I have ran the code as python main.py input_images/t1.bmp
but got the error :
ValueError: Input dimension mis-match. (input[1].shape[1] = 3, input[2].shape[1] = 64)
Apply node that caused the error: Elemwise{Composite{(i0 * ((i1 + i2) + Abs((i1 + i2))))}}[(0, 1)](TensorConstant{(1, 1, 1, 1) of 0.5}, CorrMM{half, (1, 1), (1, 1)}.0, InplaceDimShuffle{x,0,x,x}.0)
Toposort index: 19
Inputs types: [TensorType(float32, (True, True, True, True)), TensorType(float32, 4D), TensorType(float32, (True, False, True, True))]
Inputs shapes: [(1, 1, 1, 1), (128, 3, 9, 8), (1, 64, 1, 1)]
Inputs strides: [(4, 4, 4, 4), (864, 288, 32, 4), (256, 4, 4, 4)]
Inputs values: [array([[[[ 0.5]]]], dtype=float32), 'not shown', 'not shown']
Outputs clients: [[CorrMM{half, (1, 1), (1, 1)}(Elemwise{Composite{(i0 * ((i1 + i2) + Abs((i1 + i2))))}}[(0, 1)].0, Subtensor{::, ::, ::int64, ::int64}.0), Elemwise{Composite{(i0 + (i1 * ((i2 + i3) + Abs((i2 + i3)))))}}[(0, 0)](Elemwise{Composite{(i0 * ((i1 + i2) + Abs((i1 + i2))))}}[(0, 1)].0, TensorConstant{(1, 1, 1, 1) of 0.5}, CorrMM_gradInputs{half, (1, 1), (1, 1)}.0, InplaceDimShuffle{x,0,x,x}.0)]]

ValueError: CorrMM images and kernel must have the same stack size

The following error happens when I try to run model on an example image:

$ python main.py "experiments/butterfly-0.5x.bmp" --model=sr --scale=2
Using Theano backend.
Old Size :  (128, 128, 3)
New Size : (256, 256, 3)
Number of patches = 62001, Patch Shape = (8, 8)
Model loaded.
Traceback (most recent call last):
  File "/Users/dante/anaconda/lib/python3.5/site-packages/theano/compile/function_module.py", line 859, in __call__
    outputs = self.fn()
ValueError: CorrMM images and kernel must have the same stack size


During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "main.py", line 50, in <module>
    model.upscale(path, save_intermediate=save, mode=mode, patch_size=patch_size, suffix=suffix)
  File "/Users/dante/Developer/udacity/sdc/samples/Image-Super-Resolution/models.py", line 186, in upscale
    result = model.predict(img_conv, batch_size=128, verbose=verbose)
  File "/Users/dante/anaconda/lib/python3.5/site-packages/keras/engine/training.py", line 1219, in predict
    batch_size=batch_size, verbose=verbose)
  File "/Users/dante/anaconda/lib/python3.5/site-packages/keras/engine/training.py", line 897, in _predict_loop
    batch_outs = f(ins_batch)
  File "/Users/dante/anaconda/lib/python3.5/site-packages/keras/backend/theano_backend.py", line 919, in __call__
    return self.function(*inputs)
  File "/Users/dante/anaconda/lib/python3.5/site-packages/theano/compile/function_module.py", line 871, in __call__
    storage_map=getattr(self.fn, 'storage_map', None))
  File "/Users/dante/anaconda/lib/python3.5/site-packages/theano/gof/link.py", line 314, in raise_with_op
    reraise(exc_type, exc_value, exc_trace)
  File "/Users/dante/anaconda/lib/python3.5/site-packages/six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "/Users/dante/anaconda/lib/python3.5/site-packages/theano/compile/function_module.py", line 859, in __call__
    outputs = self.fn()
ValueError: CorrMM images and kernel must have the same stack size

Apply node that caused the error: CorrMM{half, (1, 1)}(InplaceDimShuffle{0,3,1,2}.0, Subtensor{::, ::, ::int64, ::int64}.0)
Toposort index: 12
Inputs types: [TensorType(float32, 4D), TensorType(float32, 4D)]
Inputs shapes: [(128, 3, 8, 8), (9, 9, 64, 3)]
Inputs strides: [(768, 4, 96, 12), (4, 36, -972, -324)]
Inputs values: ['not shown', 'not shown']
Outputs clients: [[Elemwise{Composite{(i0 * (Abs((i1 + i2)) + i1 + i2))}}[(0, 1)](TensorConstant{(1, 1, 1, 1) of 0.5}, CorrMM{half, (1, 1)}.0, InplaceDimShuffle{0,3,1,2}.0)]]

Backtrace when the node is created(use Theano flag traceback.limit=N to make it longer):
  File "main.py", line 50, in <module>
    model.upscale(path, save_intermediate=save, mode=mode, patch_size=patch_size, suffix=suffix)
  File "/Users/dante/Developer/udacity/sdc/samples/Image-Super-Resolution/models.py", line 182, in upscale
    model = self.create_model(img_height, img_width, load_weights=True)
  File "/Users/dante/Developer/udacity/sdc/samples/Image-Super-Resolution/models.py", line 475, in create_model
    x = Convolution2D(self.n1, self.f1, self.f1, activation='relu', border_mode='same', name='level1')(init)
  File "/Users/dante/anaconda/lib/python3.5/site-packages/keras/engine/topology.py", line 569, in __call__
    self.add_inbound_node(inbound_layers, node_indices, tensor_indices)
  File "/Users/dante/anaconda/lib/python3.5/site-packages/keras/engine/topology.py", line 632, in add_inbound_node
    Node.create_node(self, inbound_layers, node_indices, tensor_indices)
  File "/Users/dante/anaconda/lib/python3.5/site-packages/keras/engine/topology.py", line 164, in create_node
    output_tensors = to_list(outbound_layer.call(input_tensors[0], mask=input_masks[0]))
  File "/Users/dante/anaconda/lib/python3.5/site-packages/keras/layers/convolutional.py", line 442, in call
    filter_shape=self.W_shape)
  File "/Users/dante/anaconda/lib/python3.5/site-packages/keras/backend/theano_backend.py", line 1454, in conv2d
    filter_shape=filter_shape)

I use Python 3.5.2, Theano 0.8.2, and Keras 1.2.0.

ValueError

$ python main.py "C:\Users\Kazusasukina\PycharmProjects\Image-Super-Resolution-master\results\lenna.bmp" --model=ddsr
D:\environment\python\python35\lib\site-packages\h5py_init_.py:36: FutureWarning: Conversion of the second argument of issubdtype from float to np.floating is deprecated. In future, it will be treated as np.float64 == np.dtype(float).type.
from ._conv import register_converters as _register_converters
Using TensorFlow backend.
Old Size : (512, 512, 3)
New Size : (1024, 1024, 3)
Number of patches = 1034289, Patch Shape = (8, 8)
Saving intermediate image.
Traceback (most recent call last):
File "D:\environment\python\python35\lib\site-packages\tensorflow\python\framework\common_shapes.py", line 686, in _call_cpp_shape_fn_impl
input_tensors_as_shapes, status)
File "D:\environment\python\python35\lib\site-packages\tensorflow\python\framework\errors_impl.py", line 473, in exit
c_api.TF_GetCode(self.status.status))
tensorflow.python.framework.errors_impl.InvalidArgumentError: Dimension 2 in both shapes must be equal, but are 3 and 64 for 'Assign' (op: 'Assign') with input shapes: [3,3,3,64], [3,3,64,3].

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "main.py", line 57, in
model.upscale(p, save_intermediate=save, mode=mode, patch_size=patch_size, suffix=suffix)
File "C:\Users\Kazusasukina\PycharmProjects\Image-Super-Resolution-master\models.py", line 202, in upscale
model = self.create_model(img_dim_2, img_dim_1, load_weights=True)
File "C:\Users\Kazusasukina\PycharmProjects\Image-Super-Resolution-master\models.py", line 659, in create_model
if load_weights: model.load_weights(self.weight_path)
File "D:\environment\python\python35\lib\site-packages\keras\engine\topology.py", line 2656, in load_weights
f, self.layers, reshape=reshape)
File "D:\environment\python\python35\lib\site-packages\keras\engine\topology.py", line 3382, in load_weights_from_hdf5_group
K.batch_set_value(weight_value_tuples)
File "D:\environment\python\python35\lib\site-packages\keras\backend\tensorflow_backend.py", line 2368, in batch_set_value
assign_op = x.assign(assign_placeholder)
File "D:\environment\python\python35\lib\site-packages\tensorflow\python\ops\variables.py", line 573, in assign
return state_ops.assign(self._variable, value, use_locking=use_locking)
File "D:\environment\python\python35\lib\site-packages\tensorflow\python\ops\state_ops.py", line 276, in assign
validate_shape=validate_shape)
File "D:\environment\python\python35\lib\site-packages\tensorflow\python\ops\gen_state_ops.py", line 56, in assign
use_locking=use_locking, name=name)
File "D:\environment\python\python35\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 787, in _apply_op_helper
op_def=op_def)
File "D:\environment\python\python35\lib\site-packages\tensorflow\python\framework\ops.py", line 2958, in create_op
set_shapes_for_outputs(ret)
File "D:\environment\python\python35\lib\site-packages\tensorflow\python\framework\ops.py", line 2209, in set_shapes_for_outputs
shapes = shape_func(op)
File "D:\environment\python\python35\lib\site-packages\tensorflow\python\framework\ops.py", line 2159, in call_with_requiring
return call_cpp_shape_fn(op, require_shape_fn=True)
File "D:\environment\python\python35\lib\site-packages\tensorflow\python\framework\common_shapes.py", line 627, in call_cpp_shape_fn
require_shape_fn)
File "D:\environment\python\python35\lib\site-packages\tensorflow\python\framework\common_shapes.py", line 691, in _call_cpp_shape_fn_impl
raise ValueError(err.message)
ValueError: Dimension 2 in both shapes must be equal, but are 3 and 64 for 'Assign' (op: 'Assign') with input shapes: [3,3,3,64], [3,3,64,3].

I came across this problem and had no idea about how to figure this out @titu1994 ,may you help~ thanks

ValueError: CorrMM images and kernel must have the same stack size

Hi, I am fairly new to Keras. I was trying to the run the network on an image. But I end up getting this error.

`Using Theano backend.
Old Size : (480, 500, 3)
New Size : (1000, 960, 3)
Number of patches = 946329, Patch Shape = (8, 8)
Model loaded.
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/theano/compile/function_module.py", line 884, in call
self.fn() if output_subset is None else
ValueError: CorrMM images and kernel must have the same stack size

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "main.py", line 50, in
model.upscale(path, save_intermediate=save, mode=mode, patch_size=patch_size, suffix=suffix)
File "/media/shreyas/6E726CFB726CC983/Box Sync/Work/machine learning/Super resolution/Super Resolution/models.py", line 186, in upscale
result = model.predict(img_conv, batch_size=128, verbose=verbose)
File "/usr/local/lib/python3.5/dist-packages/keras/engine/training.py", line 1506, in predict
batch_size=batch_size, verbose=verbose)
File "/usr/local/lib/python3.5/dist-packages/keras/engine/training.py", line 1130, in _predict_loop
batch_outs = f(ins_batch)
File "/usr/local/lib/python3.5/dist-packages/keras/backend/theano_backend.py", line 1197, in call
return self.function(*inputs)
File "/usr/local/lib/python3.5/dist-packages/theano/compile/function_module.py", line 898, in call
storage_map=getattr(self.fn, 'storage_map', None))
File "/usr/local/lib/python3.5/dist-packages/theano/gof/link.py", line 325, in raise_with_op
reraise(exc_type, exc_value, exc_trace)
File "/usr/lib/python3/dist-packages/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/usr/local/lib/python3.5/dist-packages/theano/compile/function_module.py", line 884, in call
self.fn() if output_subset is None else
ValueError: CorrMM images and kernel must have the same stack size

Apply node that caused the error: CorrMM{half, (1, 1), (1, 1)}(InplaceDimShuffle{0,3,1,2}.0, Subtensor{::, ::, ::int64, ::int64}.0)
Toposort index: 18
Inputs types: [TensorType(float32, 4D), TensorType(float32, 4D)]
Inputs shapes: [(128, 3, 8, 8), (3, 64, 3, 3)]
Inputs strides: [(768, 4, 96, 12), (36, 108, -4, -12)]
Inputs values: ['not shown', 'not shown']
Outputs clients: [[Elemwise{Composite{(i0 * ((i1 + i2) + Abs((i1 + i2))))}}[(0, 1)](TensorConstant{(1, 1, 1, 1) of 0.5}, CorrMM{half, (1, 1), (1, 1)}.0, InplaceDimShuffle{x,0,x,x}.0)]]

Backtrace when the node is created(use Theano flag traceback.limit=N to make it longer):
File "main.py", line 50, in
model.upscale(path, save_intermediate=save, mode=mode, patch_size=patch_size, suffix=suffix)
File "/media/shreyas/6E726CFB726CC983/Box Sync/Work/machine learning/Super resolution/Super Resolution/models.py", line 182, in upscale
model = self.create_model(img_height, img_width, load_weights=True)
File "/media/shreyas/6E726CFB726CC983/Box Sync/Work/machine learning/Super resolution/Super Resolution/models.py", line 561, in create_model
level1_1 = Convolution2D(self.n1, (3, 3), activation='relu', padding='same')(init)
File "/usr/local/lib/python3.5/dist-packages/keras/engine/topology.py", line 596, in call
output = self.call(inputs, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/keras/layers/convolutional.py", line 164, in call
dilation_rate=self.dilation_rate)
File "/usr/local/lib/python3.5/dist-packages/keras/backend/theano_backend.py", line 1855, in conv2d
filter_dilation=dilation_rate)

HINT: Use the Theano flag 'exception_verbosity=high' for a debugprint and storage map footprint of this apply node.
`
Can you please help me to figure out this error? Do I need to try different version of Keras or Theano?
Thanks in advance

Fix for newer Keras versions

I got an error:
AttributeError: module 'keras.backend' has no attribute 'image_dim_ordering'

If you want to support newer Keras, then according to this:
keras-team/keras#12649
the method has be renamed to image_data_format.

Syntax Error in model.py

I cloned the repo and wanted to run a test image. Thus I entered the following command

python2.7 main.py "/Users/X/PNGs/test_image.png"

And received the following error message:

Traceback (most recent call last):
File "main.py", line 1, in
import models
File "./models.py", line 70
def create_model(self, height=32, width=32, channels=3, load_weights=False, batch_size=128) -> Model:
^
SyntaxError: invalid syntax

Whats the meaning here? Obviously the string "-> Model" is not part of a regular method definition...

TypeError: 'NoneType' object is not callable

Traceback (most recent call last):
File "C:/Users/DELL/Desktop/Super-Resolution-Images-master/main.py", line 41, in
for p in path():
TypeError: 'NoneType' object is not callable。In the main.py
I cannot to solve, Can you tell me how to settle it, thank so so much!

can not run the main.py! what's the issue?

(C:\Anaconda3) C:\Users\shijh\Desktop\sr\Image-Super-Resolution-master>python main.py d:\zebra.bmp"
Using Theano backend.
Old Size : (391, 586, 3)
New Size : (1172, 782, 3)
Number of patches = 902875, Patch Shape = (8, 8)
Model loaded.
Traceback (most recent call last):
File "C:\Anaconda3\lib\site-packages\theano\compile\function_module.py", line 884, in call
self.fn() if output_subset is None else
ValueError: CorrMM images and kernel must have the same stack size

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "main.py", line 50, in
model.upscale(path, save_intermediate=save, mode=mode, patch_size=patch_size, suffix=suffix)
File "C:\Users\shijh\Desktop\sr\Image-Super-Resolution-master\models.py", line 186, in upscale
result = model.predict(img_conv, batch_size=128, verbose=verbose)
File "C:\Anaconda3\lib\site-packages\keras\engine\training.py", line 1713, in predict
verbose=verbose, steps=steps)
File "C:\Anaconda3\lib\site-packages\keras\engine\training.py", line 1269, in _predict_loop
batch_outs = f(ins_batch)
File "C:\Anaconda3\lib\site-packages\keras\backend\theano_backend.py", line 1222, in call
return self.function(*inputs)
File "C:\Anaconda3\lib\site-packages\theano\compile\function_module.py", line 898, in call
storage_map=getattr(self.fn, 'storage_map', None))
File "C:\Anaconda3\lib\site-packages\theano\gof\link.py", line 325, in raise_with_op
reraise(exc_type, exc_value, exc_trace)
File "C:\Anaconda3\lib\site-packages\six.py", line 685, in reraise
raise value.with_traceback(tb)
File "C:\Anaconda3\lib\site-packages\theano\compile\function_module.py", line 884, in call
self.fn() if output_subset is None else
ValueError: CorrMM images and kernel must have the same stack size

Apply node that caused the error: CorrMM{half, (1, 1), (1, 1)}(InplaceDimShuffle{0,3,1,2}.0, Subtensor{::, ::, ::int64, ::int64}.0)
Toposort index: 18
Inputs types: [TensorType(float32, 4D), TensorType(float32, 4D)]
Inputs shapes: [(128, 3, 8, 8), (3, 64, 3, 3)]
Inputs strides: [(768, 4, 96, 12), (36, 108, -4, -12)]
Inputs values: ['not shown', 'not shown']
Outputs clients: [[Elemwise{Composite{(i0 * ((i1 + i2) + Abs((i1 + i2))))}}[(0, 1)](TensorConstant{(1, 1, 1, 1) of 0.5}, CorrMM{half, (1, 1), (1, 1)}.0, InplaceDimShuffle{x,0,x,x}.0)]]

Backtrace when the node is created(use Theano flag traceback.limit=N to make it longer):
File "main.py", line 50, in
model.upscale(path, save_intermediate=save, mode=mode, patch_size=patch_size, suffix=suffix)
File "C:\Users\shijh\Desktop\sr\Image-Super-Resolution-master\models.py", line 182, in upscale
model = self.create_model(img_height, img_width, load_weights=True)
File "C:\Users\shijh\Desktop\sr\Image-Super-Resolution-master\models.py", line 561, in create_model
level1_1 = Convolution2D(self.n1, (3, 3), activation='relu', padding='same')(init)
File "C:\Anaconda3\lib\site-packages\keras\engine\topology.py", line 602, in call
output = self.call(inputs, **kwargs)
File "C:\Anaconda3\lib\site-packages\keras\layers\convolutional.py", line 164, in call
dilation_rate=self.dilation_rate)
File "C:\Anaconda3\lib\site-packages\keras\backend\theano_backend.py", line 1890, in conv2d
filter_dilation=dilation_rate)

HINT: Use the Theano flag 'exception_verbosity=high' for a debugprint and storage map footprint of this apply node.

who can help me? thank you!

Expected binary or unicode string, got (None, 8, 8, 3)

Hello, I have tried to run the code exactly as you specified using the following command:

python main.py "/home/moataz/Downloads/Image-Super-Resolution-master/input_images/t10.bmp"

But it gave me the following error at the end:
Not sure if I am doing something wrong

Using TensorFlow backend.
Old Size : (129, 142, 3)
New Size : (284, 258, 3)
Number of patches = 69527, Patch Shape = (8, 8)
Traceback (most recent call last):
File "main.py", line 51, in
model.upscale(path, save_intermediate=save, mode=mode, patch_size=patch_size, suffix=suffix)
File "/home/moataz/Downloads/Image-Super-Resolution-master/models.py", line 180, in upscale
model = self.create_model(img_height, img_width, load_weights=True)
File "/home/moataz/Downloads/Image-Super-Resolution-master/models.py", line 531, in create_model
level2_2 = Deconvolution2D(self.n1, 3, 3, activation=u'relu', output_shape=output_shape, border_mode=u'same')(level2_1)
File "/usr/local/lib/python2.7/dist-packages/keras/engine/topology.py", line 514, in call
self.add_inbound_node(inbound_layers, node_indices, tensor_indices)
File "/usr/local/lib/python2.7/dist-packages/keras/engine/topology.py", line 572, in add_inbound_node
Node.create_node(self, inbound_layers, node_indices, tensor_indices)
File "/usr/local/lib/python2.7/dist-packages/keras/engine/topology.py", line 149, in create_node
output_tensors = to_list(outbound_layer.call(input_tensors[0], mask=input_masks[0]))
File "/usr/local/lib/python2.7/dist-packages/keras/layers/convolutional.py", line 656, in call
filter_shape=self.W_shape)
File "/usr/local/lib/python2.7/dist-packages/keras/backend/tensorflow_backend.py", line 1674, in deconv2d
padding=padding)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/nn_ops.py", line 278, in conv2d_transpose
output_shape_ = ops.convert_to_tensor(output_shape, name="output_shape")
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 657, in convert_to_tensor
ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/constant_op.py", line 180, in _constant_tensor_conversion_function
return constant(v, dtype=dtype, name=name)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/constant_op.py", line 163, in constant
tensor_util.make_tensor_proto(value, dtype=dtype, shape=shape))
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/tensor_util.py", line 422, in make_tensor_proto
tensor_proto.string_val.extend([compat.as_bytes(x) for x in proto_values])
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/util/compat.py", line 64, in as_bytes
(bytes_or_text,))
TypeError: Expected binary or unicode string, got (None, 8, 8, 3)

scaling factor is not working at all

hi,

when we try to train on our own dataset, your scaling factor is not working at all.

the code is so poor written, takes me so long to fix your bug.

Error due to layer incompatibility, reshaping the data.

The given below is the error I've got.

Epoch 1/25
WARNING:tensorflow:Model was constructed with shape (None, 18729, 2, 1) for input KerasTensor(type_spec=TensorSpec(shape=(None, 18729, 2, 1), dtype=tf.float32, name='conv2d_16_input'), name='conv2d_16_input', description="created by layer 'conv2d_16_input'"), but it was called on an input with incompatible shape (None, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1).

ValueError Traceback (most recent call last)
in ()
5 from keras.utils import to_categorical
6
----> 7 history=model.fit(X_train_scaled,Y_train_scaled,epochs=25,validation_data=(X_train_scaled,Y_train_scaled))
8 #history=model.fit(X_train_scaled,Y_train_scaled,batch_size=32,epochs=100,verbose=2,validation_split=0.8)
9 print(model.summary())

9 frames
/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)
975 except Exception as e: # pylint:disable=broad-except
976 if hasattr(e, "ag_error_metadata"):
--> 977 raise e.ag_error_metadata.to_exception(e)
978 else:
979 raise

ValueError: in user code:

/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/training.py:805 train_function  *
    return step_function(self, iterator)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/training.py:795 step_function  **
    outputs = model.distribute_strategy.run(run_step, args=(data,))
/usr/local/lib/python3.7/dist-packages/tensorflow/python/distribute/distribute_lib.py:1259 run
    return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/distribute/distribute_lib.py:2730 call_for_each_replica
    return self._call_for_each_replica(fn, args, kwargs)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/distribute/distribute_lib.py:3417 _call_for_each_replica
    return fn(*args, **kwargs)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/training.py:788 run_step  **
    outputs = model.train_step(data)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/training.py:754 train_step
    y_pred = self(x, training=True)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/base_layer.py:1012 __call__
    outputs = call_fn(inputs, *args, **kwargs)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/sequential.py:375 call
    return super(Sequential, self).call(inputs, training=training, mask=mask)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/functional.py:425 call
    inputs, training=training, mask=mask)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/functional.py:560 _run_internal_graph
    outputs = node.layer(*args, **kwargs)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/base_layer.py:1012 __call__
    outputs = call_fn(inputs, *args, **kwargs)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/layers/convolutional.py:248 call
    outputs = self._convolution_op(inputs, self.kernel)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/util/dispatch.py:201 wrapper
    return target(*args, **kwargs)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/ops/nn_ops.py:1020 convolution_v2
    name=name)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/ops/nn_ops.py:1150 convolution_internal
    name=name)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/ops/nn_ops.py:2615 _conv2d_expanded_batch
    name=name)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/ops/nn_ops.py:313 squeeze_batch_dims
    out_reshaped = op(inp_reshaped)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/ops/gen_nn_ops.py:973 conv2d
    data_format=data_format, dilations=dilations, name=name)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/op_def_library.py:750 _apply_op_helper
    attrs=attr_protos, op_def=op_def)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/func_graph.py:592 _create_op_internal
    compute_device)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/ops.py:3536 _create_op_internal
    op_def=op_def)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/ops.py:2016 __init__
    control_input_ops, op_def)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/ops.py:1856 _create_c_op
    raise ValueError(str(e))

ValueError: Negative dimension size caused by subtracting 18729 from 1 for '{{node sequential_20/conv2d_16/Conv2D/Conv2D}} = Conv2D[T=DT_FLOAT, data_format="NHWC", dilations=[1, 1, 1, 1], explicit_paddings=[], padding="VALID", strides=[1, 1, 1, 1], use_cudnn_on_gpu=true](sequential_20/conv2d_16/Conv2D/Reshape, sequential_20/conv2d_16/Conv2D/Conv2D/ReadVariableOp)' with input shapes: [?,1,1,1], [18729,2,1,1].

The code is this:

%tensorflow_version 2.3

import tensorflow as tf
X_Train = X_train_scaled.reshape(X_train.shape + (-1,))
print(X_Train.shape) # (8000,20,32,1)
Y_Train = Y_train_scaled.reshape( Y_train.shape+ (-1,))
print(Y_Train.shape) # (8000,20,32,1)

model = tf.keras.models.Sequential([ tf.keras.layers.Conv2D(1, (18729,2), input_shape=(18729,2,1))])

model.compile(loss='mse', optimizer='rmsprop',metrics=['accuracy'])
print ('compilation time : ', time.time() - start)

ValueError: could not broadcast input array from shape (3,32,32) into shape (3,64,64)

C:\Users\Shreyas\Image-Super-Resolution\Image-Super-Resolution>python tests.py
Using TensorFlow backend.
2018-04-10 12:19:18.301435: I C:\tf_jenkins\workspace\rel-win\M\windows\PY\36\tensorflow\core\platform\cpu_feature_guard.cc:140] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2
Training model : ImageSuperResolutionModel
Epoch 1/250
Found 364 images.
Traceback (most recent call last):
File "tests.py", line 48, in
sr.fit(nb_epochs=250)
File "C:\Users\Shreyas\Image-Super-Resolution\Image-Super-Resolution\models.py", line 516, in fit
return super(ImageSuperResolutionModel, self).fit(batch_size, nb_epochs, save_history, history_fn)
File "C:\Users\Shreyas\Image-Super-Resolution\Image-Super-Resolution\models.py", line 122, in fit
validation_steps=val_count // batch_size + 1)
File "C:\Users\Shreyas\AppData\Local\Programs\Python\Python36\lib\site-packages\keras\legacy\interfaces.py", line 91, in wrapper
return func(*args, **kwargs)
File "C:\Users\Shreyas\AppData\Local\Programs\Python\Python36\lib\site-packages\keras\engine\training.py", line 2192, in fit_generator
generator_output = next(output_generator)
File "C:\Users\Shreyas\AppData\Local\Programs\Python\Python36\lib\site-packages\keras\utils\data_utils.py", line 793, in get
six.reraise(value.class, value, value.traceback)
File "C:\Users\Shreyas\AppData\Local\Programs\Python\Python36\lib\site-packages\six.py", line 693, in reraise
raise value
File "C:\Users\Shreyas\AppData\Local\Programs\Python\Python36\lib\site-packages\keras\utils\data_utils.py", line 658, in _data_generator_task
generator_output = next(self._generator)
File "C:\Users\Shreyas\Image-Super-Resolution\Image-Super-Resolution\img_utils.py", line 300, in image_generator
batch_x[i] = img.transpose((2, 0, 1))
ValueError: could not broadcast input array from shape (3,32,32) into shape (3,64,64)
@titu1994 can you please help for solving this issue?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.