In [167]:
%matplotlib inline
import numpy as np
import os, string
from matplotlib import pyplot as plt
import scipy as sp
import cv2
import tensorflow as tf

img = cv2.imread('camera.jpg')
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#img = cv2.resize(img,(0,0),fx=0.5,fy=0.5)
print(img.shape,img.mean())

plt.imshow(img,cmap='gray')
plt.show()


(252, 252) 117.852796674

In [173]:
def getloss(latent):
    with tf.device('/cpu:0'):
        initial = tf.random_normal([252,latent]) * 0.256
        A = tf.Variable(initial)
        initial = tf.random_normal([latent,252]) * 0.256
        Phi = tf.Variable(initial)
        IMG=tf.placeholder("float", shape=[252,252])
        mu = 0.0001
        sparse = tf.matmul(A,Phi)
        #print(sparse.get_shape())
        loss = sparse - IMG
        loss = tf.reshape(loss,[252*252,-1])
        A_ravel = tf.reshape(A,[latent*252,-1])
        loss = 1./(252.*252.)*tf.nn.l2_loss(loss)
        regloss = loss+mu*tf.reduce_mean(tf.abs(A_ravel))#L1#tf.nn.l2_loss(A_ravel)#L2
        return regloss,loss,IMG,sparse

In [174]:
regloss1,loss1,IMG1,sparse1 = getloss(20)
regloss2,loss2,IMG2,sparse2 = getloss(50)
train_op1 = tf.train.GradientDescentOptimizer(0.2).minimize(regloss1)
train_op2 = tf.train.GradientDescentOptimizer(0.2).minimize(regloss2)
sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)
#Img_ravel = img.reshape([252,252])
#Img_ravel = Img_ravel.transpose(3,0,1,2)
for step in range(10001):
    _,test1 = sess.run([train_op1,loss1],feed_dict={IMG1:img})
    _,test2 = sess.run([train_op2,loss2],feed_dict={IMG2:img})
    if step % 1000 == 0:
        print('epoch:',step,'loss1:',test1,' loss2:',test2)

res1 = sess.run(sparse1)
res2 = sess.run(sparse2)
#print(res.shape)


epoch: 0 loss1: 8930.22  loss2: 8930.7
epoch: 1000 loss1: 182.476  loss2: 123.905
epoch: 2000 loss1: 126.544  loss2: 52.2182
epoch: 3000 loss1: 121.637  loss2: 37.1033
epoch: 4000 loss1: 120.346  loss2: 34.1509
epoch: 5000 loss1: 119.851  loss2: 33.2905
epoch: 6000 loss1: 119.598  loss2: 32.8753
epoch: 7000 loss1: 119.45  loss2: 32.6316
epoch: 8000 loss1: 119.357  loss2: 32.4735
epoch: 9000 loss1: 119.298  loss2: 32.3631
epoch: 10000 loss1: 119.259  loss2: 32.2815

In [175]:
#resImg = res.transpose([1,2,3,0])
resImg1 = res1#resImg.reshape([252,252])
resImg2 = res2
fig = plt.figure()
#ax = fig.add_subplot(131)  
#x.imshow(img,cmap='gray')
plt.imshow(img,cmap='gray')
fig = plt.figure()
ax = fig.add_subplot(121)  
ax.imshow(resImg1,cmap='gray')
#plt.imshow(resImg1,cmap='gray')
#fig = plt.figure()
ax = fig.add_subplot(122)  
ax.imshow(resImg2,cmap='gray')
#plt.imshow(resImg2,cmap='gray')
fig.show()


/usr/local/lib/python3.6/site-packages/matplotlib/figure.py:402: UserWarning: matplotlib is currently using a non-GUI backend, so cannot show the figure
  "matplotlib is currently using a non-GUI backend, "

In [ ]: