Transform an array with one flattened image per row, into an array in which images are reshaped and layed out like tiles on a floor. This function is useful for visualizing datasets whose rows are images, and also columns of matrices for transforming those rows (such as the fir
(X, img_shape, tile_shape, tile_spacing=(0, 0),
scale_rows_to_unit_interval=True,
output_pixel_vals=True)
| 18 | |
| 19 | |
| 20 | def tile_raster_images(X, img_shape, tile_shape, tile_spacing=(0, 0), |
| 21 | scale_rows_to_unit_interval=True, |
| 22 | output_pixel_vals=True): |
| 23 | """ |
| 24 | Transform an array with one flattened image per row, into an array in |
| 25 | which images are reshaped and layed out like tiles on a floor. |
| 26 | |
| 27 | This function is useful for visualizing datasets whose rows are images, |
| 28 | and also columns of matrices for transforming those rows |
| 29 | (such as the first layer of a neural net). |
| 30 | |
| 31 | :type X: a 2-D ndarray or a tuple of 4 channels, elements of which can |
| 32 | be 2-D ndarrays or None; |
| 33 | :param X: a 2-D array in which every row is a flattened image. |
| 34 | |
| 35 | :type img_shape: tuple; (height, width) |
| 36 | :param img_shape: the original shape of each image |
| 37 | |
| 38 | :type tile_shape: tuple; (rows, cols) |
| 39 | :param tile_shape: the number of images to tile (rows, cols) |
| 40 | |
| 41 | :param output_pixel_vals: if output should be pixel values (i.e. int8 |
| 42 | values) or floats |
| 43 | |
| 44 | :param scale_rows_to_unit_interval: if the values need to be scaled before |
| 45 | being plotted to [0,1] or not |
| 46 | |
| 47 | |
| 48 | :returns: array suitable for viewing as an image. |
| 49 | (See:`Image.fromarray`.) |
| 50 | :rtype: a 2-d array with same dtype as X. |
| 51 | |
| 52 | """ |
| 53 | |
| 54 | assert len(img_shape) == 2 |
| 55 | assert len(tile_shape) == 2 |
| 56 | assert len(tile_spacing) == 2 |
| 57 | |
| 58 | # The expression below can be re-written in a more C style as |
| 59 | # follows : |
| 60 | # |
| 61 | # out_shape = [0,0] |
| 62 | # out_shape[0] = (img_shape[0]+tile_spacing[0])*tile_shape[0] - |
| 63 | # tile_spacing[0] |
| 64 | # out_shape[1] = (img_shape[1]+tile_spacing[1])*tile_shape[1] - |
| 65 | # tile_spacing[1] |
| 66 | out_shape = [ |
| 67 | (ishp + tsp) * tshp - tsp |
| 68 | for ishp, tshp, tsp in zip(img_shape, tile_shape, tile_spacing) |
| 69 | ] |
| 70 | |
| 71 | if isinstance(X, tuple): |
| 72 | assert len(X) == 4 |
| 73 | # Create an output numpy ndarray to store the image |
| 74 | if output_pixel_vals: |
| 75 | out_array = numpy.zeros((out_shape[0], out_shape[1], 4), |
| 76 | dtype='uint8') |
| 77 | else: |