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()
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)
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()
In [ ]: