-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpatchworks.py
More file actions
executable file
·78 lines (65 loc) · 2.57 KB
/
patchworks.py
File metadata and controls
executable file
·78 lines (65 loc) · 2.57 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#!/usr/bin/python
import itertools
import sklearn.decomposition
import scipy.spatial
import numpy
from matcher import PCAMatcher, MeanColorMatcher
from patches import Patches
from utilities import crop, visual_compare
class Patchworks(object):
"""
Produces patchworks.
I.e. reproduces an image from a set of images using the represent method.
"""
def __init__(self, images, patch_shape, scale_factor=1, alternatives=1,
colorspace='rgb'):
if colorspace not in ('rgb', 'hsv'):
raise ValueError('Only supported colorspaces are rgb and hsv')
# store parameters
self.__colorspace = colorspace
self.__patch_shape = patch_shape
real_shape = (patch_shape[0] * scale_factor,
patch_shape[1] * scale_factor)
self.__images = [crop(image, real_shape) for image in images]
# prepare images
preprocessed = itertools.imap(self.preprocess, self.__images)
data = numpy.vstack(preprocessed)
self.match = MeanColorMatcher(data, alternatives)
# # # Helpers
def preprocess(self, patch):
"""
Perform image processing on patch before flattened.
"""
if patch.shape != self.__patch_shape:
cropped = crop(patch, self.__patch_shape)
if self.__colorspace == 'hsv':
cropped = matplotlib.colors.rgb_to_hsv(cropped)
return cropped.flatten().astype(numpy.float)
# # # Main interface
def replace(self, patch):
"""
Replace patch with one from library of images.
"""
point = self.preprocess(patch)
return self.__images[self.match(point)]
def represent(self, image):
"""
Create a patchwork representing the image.
"""
patches = Patches(image, self.__patch_shape)
replacement_patches = itertools.imap(self.replace, patches)
return patches.stack(replacement_patches)
def visualize(self, image):
patches = Patches(image, self.__patch_shape)
extract = lambda patch: self.match.transform(self.preprocess(patch))
patch_data = numpy.vstack(itertools.imap(extract, patches))
patch_data = patch_data[:, :3] # select the three principal components
visual_compare(self.match.data, patch_data)
@property
def component_images(self):
"""
Returns images of the principal components of the library of images.
"""
pca_images = (component.reshape(self.__patch_shape)
for component in self.match.components)
return pca_images