Advertisement
Guest User

Untitled

a guest
Nov 1st, 2014
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.52 KB | None | 0 0
  1. #!/usr/bin/env python
  2. #-*- coding:utf-8 -*-
  3. # Filename: bgTexture.py
  4.  
  5. """
  6. DESCRIPTION:
  7. Places objects randomly on canvas. Input for Matlab S&P algorithm.
  8. """
  9.  
  10. from scipy import ndimage, misc
  11. import numpy as np
  12. import sys
  13. import os
  14. from matplotlib import pyplot as plt
  15. from random import shuffle
  16.  
  17. xRes = 1280  # px
  18. yRes = 960
  19.  
  20. # NOTE: Adapt path to folder containing to-be-tiled objects:
  21. src = "/home/lotje/Studies/009 - Corpus project/Object stimuli/prepare experiments/StimProc/png/scaled objects round2"
  22.  
  23. def isArrayIm(v):
  24.  
  25.     """
  26.     Checks whether a value is a image-like numpy array.
  27.  
  28.     Arguments:
  29.     v   --  The value to check.
  30.  
  31.     Returns:
  32.     True if v is image-like, False otherwise.
  33.     """
  34.  
  35.     return isinstance(v, np.ndarray) and len(v.shape) in (2,3)
  36.  
  37. def isPoint(v, nDim=2):
  38.  
  39.     """
  40.     Checks whether a value is point-like, i.e. a coordinate or resolution tuple.
  41.  
  42.     Arguments:
  43.     v       --  The value to check.
  44.  
  45.     Keyword arguments:
  46.     nDim    --  The dimensionality of the point. (default=2)
  47.  
  48.     Returns:
  49.     True if v is point-like, False otherwise.
  50.     """
  51.  
  52.     if not isinstance(v, tuple):
  53.         return False
  54.     if len(v) != nDim:
  55.         return False
  56.     for i in range(nDim):
  57.         if not isinstance(v[i], int):
  58.             return False
  59.     return True
  60.  
  61. def paste(src, dst, pos):
  62.  
  63.     """
  64.     Pastes a source image onto a destination image at position pos. The paste
  65.     may occur partly outside the boundaries of the destination image.
  66.  
  67.     Arguments:
  68.     src     --  The source image as numpy array.
  69.     dst     --  The destination image as numpy array.
  70.     pos     --  The top-left position for the paste. Must be a (row, col) tuple.
  71.  
  72.     Returns:
  73.     A copy of the destination image with the source image pasted onto it.
  74.     """
  75.  
  76.     # Check arguments
  77.     if not isArrayIm(src):
  78.         raise Exception('src must be a two- or three-dimensional numpy array')
  79.     if not isArrayIm(dst):
  80.         raise Exception('dst must be a two- or three-dimensional numpy array')
  81.     if len(src.shape) != len(dst.shape):
  82.         raise Exception('src and dst must have the same number of dimensions')
  83.     if not isPoint(pos):
  84.         raise Exception('pos must be an (int, int) tuple')
  85.  
  86.     dst = dst.copy() # Copy so we don't modify in place
  87.     dstRows = dst.shape[0]
  88.     dstCols = dst.shape[1]
  89.     srcRows = src.shape[0]
  90.     srcCols = src.shape[1]
  91.     row, col = pos
  92.     # Crop the source image if (when pasted) it falls partly outside of the
  93.     # destination image
  94.     rowMargin = dstRows - row - srcRows
  95.     if rowMargin < 0:
  96.         src = src[:rowMargin]
  97.     colMargin = dstCols - col - srcCols
  98.     if colMargin < 0:
  99.         src = src[:,:colMargin]
  100.     if row < 0:
  101.         src = src[-row:]
  102.         row = 0
  103.     if col < 0:
  104.         src = src[:,-col:]
  105.         col = 0
  106.     srcRows = src.shape[0]
  107.     srcCols = src.shape[1]
  108.     # Paste with preserving transparency
  109.     if len(dst.shape) == 3 and dst.shape[2] == 4:
  110.         _rows, _cols  = np.where(src[:,:,3] != 0)
  111.         for _row, _col in zip(_rows, _cols):
  112.             dst[row+_row, col+_col] = src[_row, _col]
  113.     else:
  114.         # Paste without transparency
  115.         dst[row:row+srcRows, col:col+srcCols] = src
  116.     return dst
  117.  
  118. def createRandomBg(lSrc, dst, res=(yRes, xRes)):
  119.  
  120.     """
  121.     Creates a background surface which contains randomly placed copies of a
  122.     series of pictures that fully cover the surface.
  123.  
  124.     Arguments:
  125.     lSrc    --  A list of source images, where each source image as a numpy
  126.                 array.
  127.     dst     --  The destination image as numpy array.
  128.  
  129.     Keyword arguments:
  130.     res     --  The resolution of the output image.
  131.     """
  132.  
  133.     # Shuffle the list at the beginning over EVERY bg:
  134.     shuffle(lSrc)
  135.    
  136.     # Check arguments
  137.     if not isinstance(lSrc, list):
  138.         raise Exception('lSrc must be a list of images')
  139.     for src in lSrc:
  140.         if not isArrayIm(src):
  141.             raise Exception(
  142.                 'Items in lSrc must be two- or three-dimensional numpy arrays')
  143.     if not isArrayIm(dst):
  144.         raise Exception('dst must be a two- or three-dimensional numpy array')
  145.     if len(src.shape) != len(dst.shape):
  146.         raise Exception('src and dst must have the same number of dimensions')
  147.     if not isPoint(res):
  148.         raise Exception('res must be an (int, int) tuple')
  149.  
  150.     cycle = 0
  151.     while True:
  152.         # Get a list of indices where the alpha channel is 0 (i.e. transparent)
  153.         rows, cols = np.where(dst[:,:,3] == 0)
  154.         # Break the loop if there are no more transparent pixels
  155.         if len(rows) == 0:
  156.             break
  157.         print '%d: N(transparent) == %d' % (cycle, np.sum(dst[:,:,3] == 0))
  158.         # Get a random transparent pixel
  159.         i = np.random.randint(0, len(rows))
  160.         row = rows[i]
  161.         col = cols[i]
  162.         print '%d: dst:empty %d:(%d, %d)' % (cycle, i, row, col)
  163.         # Get a random image and a random non-transparent pixel in this image
  164.         src = np.random.choice(lSrc)
  165.         rows, cols = np.where(src[:,:,3] != 0)
  166.         i = np.random.randint(0, len(rows)-1)
  167.         _row = rows[i]
  168.         _col = cols[i]
  169.         print '%d: src:non-empty %d:(%d, %d)' % (cycle, i, _row, _col)
  170.         # Pase the input image into the output image
  171.         print '%d: Paste @ (%d,%d)' % (cycle, row-_row, col-_col)
  172.         dst = paste(src, dst, (row-_row, col-_col))
  173.         cycle += 1
  174.     return dst
  175.  
  176. def listOfArrays(src):
  177.    
  178.     """
  179.     Opens .npy files as numpy arrays and adds them all to a big list
  180.     (input for createRandomBg)
  181.    
  182.     src     --- Source to numpy arrays
  183.     """
  184.    
  185.     l = []
  186.    
  187.     for f in os.listdir(src):
  188.         print f
  189.         fPath = os.path.join(src, f)
  190.         im = ndimage.imread(fPath)
  191.         l.append(im)
  192.     return l
  193.  
  194. def bgTexture(res = (yRes, xRes)):
  195.    
  196.     """
  197.     Generate background tiled with Hemera objects
  198.     """
  199.     lSrc = listOfArrays(src)
  200.     # Create empty array, fill with bg, and save:
  201.     a = np.zeros( (res[0], res[1], 4), dtype=np.uint8)
  202.     a = createRandomBg(lSrc, a, res = res)
  203.     plt.imshow(a)
  204.     misc.imsave("background.png", a)
  205.    
  206. if __name__ == "__main__":
  207.    
  208.     bgTexture()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement