Skip to content

Commit d9d5746

Browse files
committed
added image_analysis code
1 parent fef7587 commit d9d5746

File tree

12 files changed

+24776
-987
lines changed

12 files changed

+24776
-987
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ data_copy/*
44
data_01_11_0549/*
55
worm_algorithm/src/worm_ising_2d
66
worm_algorithm/5itergraphter.ipynb
7+
worm_algorithm/image_analysis/data/*
78

89
*.pyc
910
*.tex

worm_algorithm/count_bonds.py

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,9 @@ def __init__(self, L, block_val=None, num_blocks=10,
6565
)
6666
else:
6767
self._save_dir = save_dir
68+
if not os.path.exists(self._save_dir): # ensure save_dir exists
69+
os.makedirs(self._save_dir) # create directory if not
70+
6871
config_files = os.listdir(self._data_dir)
6972
self._config_files = sorted([
7073
self._data_dir + i for i in config_files if i.endswith('.txt')
@@ -182,11 +185,26 @@ def count_bonds(self):
182185
self.bond_stats[key] = [val[0], err[0], val[1], err[1]]
183186
del(data)
184187

188+
# def _save_batch(self, data):
189+
"""Save in progress bond_stats data to .txt file."""
190+
# save_file = self._save_dir + f'bond_stats_{self._L}_in_progress.txt'
191+
# save_file_copy = save_file + '.bak'
192+
# orig_exists = os.path.exists(save_file)
193+
# copy exists = os.path.exists(save_file_copy)
194+
# if orig exists:
195+
# shutil.copy(save_file, save_file_copy)
196+
# if copy_exists:
197+
# os.remove(save_file)
198+
# ordered_bond_stats = OrderedDict(sorted(self.bond_stats.items(),
199+
# key=lambda t: t[0]))
200+
# with open(save_file, 'w') as f:
201+
# for key, val in ordered_bond_stats.items():
202+
# f.write(f'{key} {val[0]} {val[1]} {val[2]} {val[3]}')
203+
204+
185205

186206
def _save(self):
187207
"""Save bond_stats data to .txt file."""
188-
if not os.path.exists(self._save_dir):
189-
os.makedirs(self._save_dir)
190208
save_file = self._save_dir + 'bond_stats_{}.txt'.format(self._L)
191209
save_file_copy = save_file + '.bak'
192210
orig_exists = os.path.exists(save_file)

worm_algorithm/generate_data.ipynb

Lines changed: 88 additions & 209 deletions
Large diffs are not rendered by default.

worm_algorithm/image_analysis/__init__.py

Whitespace-only changes.

worm_algorithm/image_analysis/closetooriginal-Copy1.ipynb

Lines changed: 714 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
import numpy as np
2+
import matplotlib.pyplot as plt
3+
import scipy.misc
4+
import math
5+
import itertools
6+
7+
def show(image):
8+
fig, ax = plt.subplots()
9+
img = ax.imshow(image, cmap='Greys', aspect=1, interpolation='none')
10+
plt.colorbar(img)
11+
return fig, ax
12+
13+
class Image(object):
14+
"""Class to identify boundaries between black and white pixels in image.
15+
"""
16+
def __init__(self, image_file):
17+
#self.cutoff = cutoff
18+
try:
19+
self._image_orig = scipy.misc.imread(image_file, "mode=L")
20+
except FileNotFoundError:
21+
raise f"Unable to load from {image_file}"
22+
self._Nx, self._Ny = self._image_orig.shape
23+
self._image_flat = self._image_orig.flatten()
24+
self._image = np.reshape(1 - self._image_flat / 255.0,
25+
(self._Nx, self._Ny))
26+
self._image_cropped = None
27+
self._image_bw = None
28+
self._image_links = None
29+
#self._original = self._image.copy()
30+
31+
# def show(self, image=None):
32+
# """Create figure containing image, return figure and axes instances."""
33+
# if image is None:
34+
# image = self._image
35+
# fig, ax = plt.subplots()
36+
# img = ax.imshow(image, cmap='Greys', aspect=1,
37+
# interpolation='none')
38+
# plt.colorbar(img)
39+
# return fig, ax
40+
41+
def crop(self, x_start, y_start, x_end, y_end):
42+
"""Crop image from (x_start, y_start) to (x_end, y_end)."""
43+
cropped_image = self._image[x_start:x_end, y_start:y_end]
44+
self._image_cropped = cropped_image
45+
#self._image = cropped_image
46+
return cropped_image
47+
48+
def _cutoff(self, cutoff, image=None):
49+
"""Convert image from greyscale to exclusively black and white,
50+
determined by the value of cutoff."""
51+
if image is None:
52+
image = self._image
53+
image_flat = np.ndarray.flatten(image)
54+
Nx, Ny = image.shape
55+
#n_sites = image.shape[0] * image.shape[1]
56+
image_bw = np.array([-1 if i < cutoff else 1 for i in image_flat])
57+
image_bw = (np.reshape(image_bw, (Nx, Ny)) + 1) / 2.0
58+
self._image_bw = image_bw
59+
return image_bw
60+
61+
def get_boundaries(self, cutoff, image=None):
62+
"""Identify boundaries separating black and white regions of image."""
63+
if image is None:
64+
image = self._image
65+
image_bw = self._cutoff(cutoff, image)
66+
Nx, Ny = image_bw.shape
67+
links_arr = np.zeros((Nx, Ny, 2))
68+
for x, y in itertools.product(range(Nx), range(Ny)):
69+
links_arr[(x+1)%Nx, y, 1] = (int(round(image_bw[x, y]))
70+
+ int(round(image_bw[(x+1)%Nx, y])))%2
71+
links_arr[x, (y+1)%Ny, 0] = (int(round(image_bw[x, y]))
72+
+ int(round(image_bw[x, (y+1)%Ny])))%2
73+
image_links = np.zeros((2*Nx, 2*Ny), dtype=int)
74+
for x, y in itertools.product(range(Nx), range(Ny)):
75+
image_links[2*x+1, 2*y] = links_arr[x, y, 0]
76+
image_links[2*x, 2*y+1] = links_arr[x, y, 1]
77+
link_sum = (links_arr[x, y, 0] + links_arr[x, y, 1]
78+
+ links_arr[(x-1)%Nx, y, 0] + links_arr[x, (y-1)%Ny, 1])
79+
if link_sum != 0:
80+
image_links[2*x, 2*y] = 1
81+
self._image_links = image_links
82+
return image_links
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import os
2+
import subprocess
3+
import sys
4+
import argparse
5+
6+
def download_mnist():
7+
"""Download mnist dataset into 'mnist/' directory."""
8+
current_dir = os.getcwd()
9+
mnist_data_dir = '../data/mnist/'
10+
if not os.path.exists(mnist_data_dir):
11+
os.makedirs(mnist_data_dir)
12+
os.chdir(mnist_data_dir)
13+
os.system('curl -O http://deeplearning.net/data/mnist/mnist.pkl.gz')
14+
os.chdir(current_dir)
15+
mnist_data_file = mnist_data_dir.join('mnist.pkl.gz')
16+
if os.path.isfile(mnist_data_file):
17+
print(f"Successfully downloaded mnist data file to: {mnist_data_file}")
18+
19+
20+
if __name__ == '__main__':
21+
download_mnist()
22+
23+

0 commit comments

Comments
 (0)