-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathexample_image.py
52 lines (41 loc) · 1.79 KB
/
example_image.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import scipy.misc
import pyae
import numpy
import matplotlib.pyplot
# Example for encoding an image using the PyAE module.
# This example only returns the floating-point value that encodes the image.
# Check the example_image_binary.py to return the binary code of the floating-point value.
# Change the precision to a bigger value
from decimal import getcontext
getcontext().prec = 444
# Read an image.
im = scipy.misc.face(gray=True)
# Just work on a small part to save time. The larger the image, the more time consumed.
im = im[:15, :15]
# Convert the image into a 1D vector.
msg = im.flatten()
# Create the frequency table based on its hitogram.
hist, bin_edges = numpy.histogram(a=im,
bins=range(0, 257))
frequency_table = {key: value for key, value in zip(bin_edges[0:256], hist)}
# Create an instance of the ArithmeticEncoding class.
AE = pyae.ArithmeticEncoding(frequency_table=frequency_table)
# Encode the message
encoded_msg, encoder, interval_min_value, interval_max_value = AE.encode(msg=msg,
probability_table=AE.probability_table)
# Decode the message
decoded_msg, decoder = AE.decode(encoded_msg=encoded_msg,
msg_length=len(msg),
probability_table=AE.probability_table)
# Reshape the image to its original shape.
decoded_msg = numpy.reshape(decoded_msg, im.shape)
# Show the original and decoded images.
fig, ax = matplotlib.pyplot.subplots(1, 2)
ax[0].imshow(im, cmap="gray")
ax[0].set_title("Original Image")
ax[0].set_xticks([])
ax[0].set_yticks([])
ax[1].imshow(decoded_msg, cmap="gray")
ax[1].set_title("Reconstructed Image")
ax[1].set_xticks([])
ax[1].set_yticks([])