changeset 950:faa658da89c2

tweaks to image_tiling
author James Bergstra <bergstrj@iro.umontreal.ca>
date Wed, 18 Aug 2010 12:59:47 -0400
parents cafa16bfc7df
children 5d70dfc70ec0
files pylearn/io/image_tiling.py
diffstat 1 files changed, 29 insertions(+), 2 deletions(-) [+]
line wrap: on
line diff
--- a/pylearn/io/image_tiling.py	Wed Aug 11 14:35:57 2010 -0400
+++ b/pylearn/io/image_tiling.py	Wed Aug 18 12:59:47 2010 -0400
@@ -11,7 +11,8 @@
     ndar *= 1.0 / (ndar.max()+eps)
     return ndar
 
-def tile_raster_images(X, img_shape, tile_shape, tile_spacing=(0,0),
+def tile_raster_images(X, img_shape, 
+        tile_shape=None, tile_spacing=(1,1),
         scale_rows_to_unit_interval=True, 
         output_pixel_vals=True
         ):
@@ -27,16 +28,26 @@
     :type img_shape: tuple; (height, width)
     :param img_shape: the original shape of each image
     :type tile_shape: tuple; (rows, cols)
-    :param tile_shape: the number of images to tile (rows, cols)
+    :param tile_shape: the number of images to tile (rows, cols) (Defaults to a square-ish
+        shape with the right area for the number of images)
 
     :returns: array suitable for viewing as an image.  (See:`PIL.Image.fromarray`.)
     :rtype: a 2-d array with same dtype as X.
 
     """
+    if isinstance(X, tuple): 
+        n_images_in_x = X[0].shape[0]
+    else:
+        n_images_in_x = X.shape[0]
+
+    if tile_shape is None:
+        tile_shape = most_square_shape(n_images_in_x)
+
     assert len(img_shape) == 2
     assert len(tile_shape) == 2
     assert len(tile_spacing) == 2
 
+    #out_shape is the shape in pixels of the returned image array
     out_shape = [(ishp + tsp) * tshp - tsp for ishp, tshp, tsp 
         in zip(img_shape, tile_shape, tile_spacing)]
 
@@ -82,3 +93,19 @@
         return out_array
 
 
+def most_square_shape(N):
+    """rectangle (height, width) with area N that is closest to sqaure
+    """
+    for i in xrange(int(numpy.sqrt(N)),0, -1):
+        if 0 == N % i:
+            return (i, N/i)
+
+def save_tiled_raster_images(tiled_img, filename):
+    """Save a a return value from `tile_raster_images` to `filename`.
+
+    Returns the PIL image that was saved
+    """
+    img = Image.fromarray( tiled_img, 'RGBA')
+    img.save(filename)
+    return img
+