Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
| Download

📚 The CoCalc Library - books, templates and other resources

Views: 96145
License: OTHER
1
"""
2
Simple examples of convolution to do some basic filters
3
Also demonstrates the use of TensorFlow data readers.
4
5
We will use some popular filters for our image.
6
It seems to be working with grayscale images, but not with rgb images.
7
It's probably because I didn't choose the right kernels for rgb images.
8
9
kernels for rgb images have dimensions 3 x 3 x 3 x 3
10
kernels for grayscale images have dimensions 3 x 3 x 1 x 1
11
12
CS 20: "TensorFlow for Deep Learning Research"
13
cs20.stanford.edu
14
Chip Huyen ([email protected])
15
Lecture 07
16
"""
17
import os
18
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
19
20
import sys
21
sys.path.append('..')
22
23
from matplotlib import gridspec as gridspec
24
from matplotlib import pyplot as plt
25
import tensorflow as tf
26
27
import kernels
28
29
def read_one_image(filename):
30
''' This method is to show how to read image from a file into a tensor.
31
The output is a tensor object.
32
'''
33
image_string = tf.read_file(filename)
34
image_decoded = tf.image.decode_image(image_string)
35
image = tf.cast(image_decoded, tf.float32) / 256.0
36
return image
37
38
def convolve(image, kernels, rgb=True, strides=[1, 3, 3, 1], padding='SAME'):
39
images = [image[0]]
40
for i, kernel in enumerate(kernels):
41
filtered_image = tf.nn.conv2d(image,
42
kernel,
43
strides=strides,
44
padding=padding)[0]
45
if i == 2:
46
filtered_image = tf.minimum(tf.nn.relu(filtered_image), 255)
47
images.append(filtered_image)
48
return images
49
50
def show_images(images, rgb=True):
51
gs = gridspec.GridSpec(1, len(images))
52
for i, image in enumerate(images):
53
plt.subplot(gs[0, i])
54
if rgb:
55
plt.imshow(image)
56
else:
57
image = image.reshape(image.shape[0], image.shape[1])
58
plt.imshow(image, cmap='gray')
59
plt.axis('off')
60
plt.show()
61
62
def main():
63
rgb = False
64
if rgb:
65
kernels_list = [kernels.BLUR_FILTER_RGB,
66
kernels.SHARPEN_FILTER_RGB,
67
kernels.EDGE_FILTER_RGB,
68
kernels.TOP_SOBEL_RGB,
69
kernels.EMBOSS_FILTER_RGB]
70
else:
71
kernels_list = [kernels.BLUR_FILTER,
72
kernels.SHARPEN_FILTER,
73
kernels.EDGE_FILTER,
74
kernels.TOP_SOBEL,
75
kernels.EMBOSS_FILTER]
76
77
kernels_list = kernels_list[1:]
78
image = read_one_image('data/friday.jpg')
79
if not rgb:
80
image = tf.image.rgb_to_grayscale(image)
81
image = tf.expand_dims(image, 0) # make it into a batch of 1 element
82
images = convolve(image, kernels_list, rgb)
83
with tf.Session() as sess:
84
images = sess.run(images) # convert images from tensors to float values
85
show_images(images, rgb)
86
87
if __name__ == '__main__':
88
main()
89