view transformations/slant.py @ 39:17caecc92544

affine transformation using PIL
author Razvan Pascanu <r.pascanu@gmail.com>
date Tue, 02 Feb 2010 21:17:11 -0500
parents e05715e4554d
children 0f1337994716
line wrap: on
line source

#!/usr/bin/python
# coding: utf-8

'''
Author: Youssouf

this module add a slant effect to the image. 

To obtain the slant effect, each row of the array is shifted proportionately by a step
controlled by the complexity.

'''

import numpy


class Slant():
    def __init__(self, complexity=1):
        #---------- private attributes
        self.direction = 1
        self.angle = 0

        #---------- generation parameters
        self.regenerate_parameters(complexity)
        #------------------------------------------------
    
    def _get_current_parameters(self):
        return [self.angle, self.direction]
    
    def get_settings_names(self):
        return ['angle', 'direction']
    
    def regenerate_parameters(self, complexity):
        self.angle = numpy.random.uniform(0.0, complexity)
        P = numpy.random.uniform()
        self.direction = 1;
        if P < 0.5:
            self.direction = -1;
        return self._get_current_parameters()
    
    
    def transform_image(self,image):
        if self.angle == 0:
            return image
        
        ysize, xsize = image.shape
        slant = self.direction*self.angle

        output = image.copy()

        # shift all the rows
        for i in range(ysize):
            line = image[i]
            delta = round((i*slant)) % xsize
            line1 = line[:xsize-delta]
            line2 = line[xsize-delta:xsize]

            output[i][delta:xsize] = line1
            output[i][0:delta] = line2

            
        #correction to center the image
        correction = (self.direction)*round(self.angle*ysize/2)
        correction = (xsize - correction) % xsize

        # center the region
        line1 = output[0:ysize,0:xsize-correction].copy()
        line2 = output[0:ysize,xsize-correction:xsize].copy()
        output[0:ysize,correction:xsize] = line1
        output[0:ysize,0:correction] = line2


        return output
            

# Test function
def test_slant():
    img_name = "3.png"
    dest_img_name = "slanted.png"
    im = Image.open(img_name,)
    im = im.convert("L")
    image = numpy.asarray(im)


    slant = Slant()
    slant.regenerate_parameters(1)
    image = slant.transform_image(image)

    im = Image.fromarray(image.astype('uint8'), "L")
    im.save(dest_img_name)

# Test
if __name__ == '__main__':  
    import sys, os, fnmatch
    import Image

    test_slant()