11月 242018
 
First load necessary packages

import pandas as pd
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Dropout, Conv2D
import keras.backend as K
import scipy, imageio
import matplotlib.pyplot as plt
from PIL import Image
%matplotlib inline
Then show original picture of my Jeep

# 首先将图片读入为矩阵
# 我们可以用pyplot的imshow()方法来展示图片
# 这是我曾经拥有的牧马人JK Rubicon Unlimited
#
img_data = imageio.imread('./pics/wranglerJK.jpg')
print(img_data.data.shape)

img = Image.fromarray(img_data, 'RGB')
plt.imshow(img)


添加图片说明


Now, build our 2-D convolutional function that takes a custom filter matrix and comput the filtered output image matrix.
def my_init(shape, dtype=None):
new_mat = np.zeros((shape[0], shape[1], 3, 3))
for i in range(shape[0]):
for j in range(shape[1]):
new_mat[:, :, i, j] = filter_mat
return np.array(new_mat, dtype=dtype)


def MyFilter(filter_mat):
print(len(filter_mat.shape))
if len(filter_mat.shape)!=2:
print('Invalid filter matrix. It must be 2-D')
return []
else:
kernel_size=filter_mat.shape
row, col, depth = img_data.shape
input_shape=img_data.shape
filter_size = row*col*depth
print(filter_size)


model = Sequential()
model.add(Conv2D(depth,
kernel_size=kernel_size,
input_shape=input_shape,
padding='same',
activation='linear',
data_format='channels_last',
kernel_initializer=my_init,
name='Conv')
)
model.add(Dense(1, activation='linear'))
model.compile(optimizer='sgd', loss='mse')
model.summary()


inX = model.input
outputs = [layer.output for layer in model.layers if layer.name=='Conv']
functions = [K.function([inX], [out]) for out in outputs]

layer_outs = [func([img_data.reshape(1, row, col, depth)]) for func in functions]
activationLayer = layer_outs[0][0]
temp = (activationLayer-np.min(activationLayer))
normalized_activationLayer = temp/np.max( np.max(temp))
return(normalized_activationLayer.reshape(row, col, depth))
Now, insert our own fixed filter matrix and get the output, using pyplot.imshow() to display the filtered picture. This time we throw in an edge detector.
filter_mat = np.array([-1, -2, -3, 0, 0, 0, 1, 2, 3]).reshape(3, 3)

outLayer = MyFilter(filter_mat)
plt.imshow(outLayer)
Below is the filtered picture.


 
 Posted by at 2:39 上午

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)