def align_images(self, angle_space_mode, angle_space, debug=False):
        ''' The function takes a serie of images and aligns it against the
        template, outputs the resulting images into the aligned_images folder
        input:
          angle_space_mode = ("fixed"|"tree")
          angle_space = tuple (min angle, max angle, precision)
        '''
        c = 0
        if angle_space_mode == "fixed":
            self.generate_rotref(angle_space)
        elif angle_space_mode == "tree":
            self.anglestree = AnglesTree(angle_space, self.template)

        for image in self.imgs:

            if angle_space_mode == "fixed":
                # generate the fourier transform of the image
                imgft = ImgFFT(image)
                imgft.ft()

                # calculate the rotations
                smax = 0
                idxmax = 0
                for idx, temp in enumerate(self.templaterotsft):
                    corr = temp.correlate(imgft)
                    s, dx, dy = corr.find_peak(1)

                    if s > smax:
                        smax = s
                        idxmax = idx

                angle = float(self.angles_list[idxmax])
            elif angle_space_mode == "tree":
                angle = self.anglestree.analyze_image(image)

            print("angle found", angle)

            rotalgimage = deepcopy(image)
            rotalgimage.rotate(-angle)

            # calculate the shifts
            rotalgimageft = ImgFFT(rotalgimage)
            rotalgimageft.ft()

            corr = rotalgimageft.correlate(self.templateft)
            self.corrs.set_image(c, corr)

            dx, dy = corr.find_translation(1)
            self.shifts.append((dx, dy, angle))

            print("shifts:", dx, dy)

            rotalgimage.move(dx, dy)

            self.algimgs.set_image(c, rotalgimage)

            if debug:
                print("Correlated image:", c)

            c += 1
    def analyze_image(self, image):
        print("------------ Analysis image ------------")

        langle = self.langle
        rangle = self.rangle

        # reset cc values
        for angle in self.angles_nodes:
            angle.ccvalue = None

        imageft = ImgFFT(image.data)
        imageft.ft()

        #aprec = langle.angle + self.prec - rangle.angle

        while langle.angle + self.prec < rangle.angle:
            print("---------", langle.angle + self.prec, rangle.angle,
                  "-----------")
            # test the three angles
            print("Analyzing:", langle.angle, rangle.angle)

            hangle = (langle.angle + rangle.angle) / 2.
            halfangle = None
            print("halfangle", hangle)
            for anglenode in self.angles_nodes:
                if hangle == anglenode.angle:
                    print("Halfangle already existing!")
                    halfangle = anglenode

            if halfangle is None:
                print("Creating halfangle")
                halfangle = AngleNode((langle.angle + rangle.angle) / 2.,
                                      self.angles, self.template)
                self.angles_nodes.append(halfangle)

            if langle.ccvalue is None:
                cc1 = langle.template.correlate(imageft)
                b1, x, y = cc1.find_peak()
                langle.ccvalue = b1

            if halfangle.ccvalue is None:
                cc2 = halfangle.template.correlate(imageft)
                b2, x, y = cc2.find_peak()
                halfangle.ccvalue = b2

            #cc3 = rangle.template.correlte(imageft)

            print("ccs:", langle.ccvalue, halfangle.ccvalue)  #, cc3)

            if langle.ccvalue >= halfangle.ccvalue:
                rangle = halfangle
            else:
                langle = halfangle

            print("Angles: ", langle.angle, rangle.angle)

            #aprec = np.sqrt(langle.angle**2 + rangle.angle**2)

        return (langle.angle + rangle.angle) / 2.
Example #3
0
    def init_template(self):
        print("creating angle: ", self.angle)
        rot = deepcopy(self.inittemplate)

        rot.rotate(self.angle)

        rotft = ImgFFT(rot)
        rotft.ft()
        self.template = rotft

        self.angles.append(self.angle)
Example #4
0
    def align_images(self, debug=False):
        c = 0

        anglestree = AnglesTree(-1, 1, 0.1, self.template)

        for image in self.imgs:

            angle = anglestree.analyze_image(image)

            #            # generate the fourier transform of the image
            #            imgft = ImgFFT(image)
            #            imgft.ft()
            #
            #            # calculate the rotations
            #            smax = 0
            #            idxmax = 0
            #            for idx, temp in enumerate(self.templaterotsft):
            #                corr = temp.correlate(imgft)
            #                s, dx, dy = corr.find_peak(1)
            #
            #                if s > smax:
            #                    smax = s
            #                    idxmax = idx
            #
            #            angle = float(self.angles_list[idxmax])

            print("angle found", angle)

            rotalgimage = deepcopy(image)
            rotalgimage.rotate(-angle)

            # calculate the shifts
            rotalgimageft = ImgFFT(rotalgimage)
            rotalgimageft.ft()

            corr = rotalgimageft.correlate(self.templateft)
            self.corrs.set_image(c, corr)

            dx, dy = corr.find_translation(1)
            self.shifts.append((dx, dy, angle))

            print("shifts:", dx, dy)

            rotalgimage.move(dx, dy)

            self.algimgs.set_image(c, rotalgimage)

            if debug:
                print("Correlated image:", c)

            lg.info("correlated image n: " + str(c))

            c += 1
    def savegif(self, imagepath, size):
        ''' Given a class imagepath and the size of the images, saves into the
        temp folder the associated image
        '''

        # calculate ft for resizing
        imft = ImgFFT(imagepath.image.data)
        imft.ft()
        im = imft.resize_image(size[0], size[1])

        # save resized image
        imsave(imagepath.gifname, im.data, format="gif")
Example #6
0
    def savegif(self, path, gifpath, size):
        image = MyImage(path)
        image.convert2grayscale()
        image.squareit()

        # calculate ft for resizing
        imft = ImgFFT(image.data)
        imft.ft()
        im = imft.resize_image(size[0], size[1])

        imrgb = MyRGBImg(np.zeros((size[0], size[1], 3)))
        for c in range(3):
            imrgb.set_channel(im, c)

        # save resized image
        imsave(gifpath, imrgb.data, format="gif")
Example #7
0
    def generate_template(self, option, rot_precision=None):
        if type(option) is str:
            if option == "UseFirstImage":
                self.template = self.imgs.get_image(0)
                self.templateft = ImgFFT(self.template)
                self.templateft.ft()
            elif option == "Average":
                self.average(False)
                self.template = self.avg
                self.templateft = ImgFFT(self.template)
                self.templateft.ft()
            else:
                raise TemplateTypeError(option)
        elif type(option) == MyImage:
            self.template = option
            self.templateft = ImgFFT(self.template)
            self.templateft.ft()
        else:
            raise TemplateTypeError(type(option))
        lg.info("template created: {0}".format(option))

        if type(rot_precision) == tuple:

            print("Creating rotation references")

            # rot_precision format = (from, to, precision)
            frm = rot_precision[0]
            to = rot_precision[1]
            prec = rot_precision[2]
            self.angles_list = np.arange(frm, to, prec)

            print("From", frm, "to", to, "precision", prec)
            print("Total:", len(self.angles_list), "angles")
            self.templaterotsft = NpyFTArray(
                (self.subfolders["template_rot"], "template_rot_ft.npy",
                 len(self.angles_list)))
            for i, angle in enumerate(self.angles_list):
                print("creating angle: ", angle)
                rot = deepcopy(self.template)
                rot.rotate(angle)

                rotft = ImgFFT(rot)
                rotft.ft()

                self.templaterotsft.set_image(i, rotft)
Example #8
0
    def align_images(self, debug=False):
        c = 0
        for image in self.imgs:

            # generate the fourier transform of the image
            imgft = ImgFFT(image)
            imgft.ft()

            # calculate the rotations
            smax = 0
            idxmax = 0
            for idx, temp in enumerate(self.templaterotsft):
                corr = temp.correlate(imgft)
                s, dx, dy = corr.find_peak(1)

                if s > smax:
                    smax = s
                    idxmax = idx

            print("angle found", self.angles_list[idxmax])

            rotalgimage = deepcopy(image)
            rotalgimage.rotate(-self.angles_list[idxmax])

            # calculate the shifts
            rotalgimageft = ImgFFT(rotalgimage)
            rotalgimageft.ft()

            corr = rotalgimageft.correlate(self.templateft)
            self.corrs.append(corr)

            dx, dy = corr.find_translation(1)
            self.shifts.append((dx, dy))

            print("shifts:", dx, dy)

            rotalgimage.move(dx, dy)
            self.algimgs.append(rotalgimage)

            if debug:
                print("Correlated image:", c)
            lg.info("correlated image n: " + str(c))

            c += 1
    def generate_template(self, option, rot_precision=None):
        if type(option) is str:
            if option == "UseFirstImage":
                self.template = self.imgs[0]
                self.templateft = ImgFFT(self.template)
                self.templateft.ft()
            elif option == "Average":
                self.average(False)
                self.template = self.avg
                self.templateft = ImgFFT(self.template)
                self.templateft.ft()
            else:
                raise TemplateTypeError(option)
        elif type(option) == MyImage:
            self.template = option
            self.templateft = ImgFFT(self.template)
            self.templateft.ft()
        else:
            raise TemplateTypeError(type(option))

        if type(rot_precision) == tuple:

            print("Creating rotation references")

            # rot_precision format = (from, to, precision)
            frm = rot_precision[0]
            to = rot_precision[1]
            prec = rot_precision[2]
            self.angles_list = np.arange(frm, to, prec)

            print("From", frm, "to", to, "precision", prec)
            print("Total:", len(self.angles_list), "angles")

            for angle in self.angles_list:
                print("creating angle: ", angle)
                rot = deepcopy(self.template)
                rot.rotate(angle)

                rotft = ImgFFT(rot)
                rotft.ft()

                self.templaterotsft.append(rotft)
    def generate_rotref(self, angle_space):
        print("Creating rotation references")

        # rot_precision format = (from, to, precision)
        frm = angle_space[0]
        to = angle_space[1]
        prec = angle_space[2]
        self.angles_list = np.arange(frm, to, prec)

        print("From", frm, "to", to, "precision", prec)
        print("Total:", len(self.angles_list), "angles")
        self.templaterotsft = NpyFTArray(
            (self.subfolders["template_rot"], "template_rot_ft.npy",
             len(self.angles_list)))

        for i, angle in enumerate(self.angles_list):
            print("creating angle: ", angle)
            rot = deepcopy(self.template)
            rot.rotate(angle)

            rotft = ImgFFT(rot)
            rotft.ft()

            self.templaterotsft.set_image(i, rotft)
Example #11
0
class AvgFolderMem(object):

    # Initialization functions
    def __init__(self, path):
        # define the main path
        self.path = path

        # folder environment variable
        self.names = []
        self.avgpath = ""
        self.subfolders = {}

        # create the folder environment
        try:
            self.makeavgdir()
        except FileNotFoundError as e:
            print("Folder not found")
        except:
            print("WTF")

        # create log file in the avg folder
        lg.basicConfig(filename=join(self.avgpath, 'example.log'),
                       level=lg.INFO)

        # pictures
        self.init_imgs = ImageArray(self.path)
        self.imgs = NpyImageArray(
            (self.subfolders["processed_images"], "proc_imgs.npy",
             len(self.init_imgs.paths)))

        # initialize variables
        self.template = MyImage()
        self.templateft = None
        self.angles_list = []

        self.templaterotsft = None

        folder = self.subfolders["aligned_images"]
        bname = "algimage.npy"
        q = self.imgs.n
        self.algimgs = NpyImageArray((folder, bname, q))

        folder = self.subfolders["correlation_images"]
        bname = "correlation.npy"
        q = self.imgs.n
        self.corrs = NpyImageArray((folder, bname, q))

        self.shifts = []

        self.avg = MyImage()

    def refine_angles(self, min_angle, max_angle):
        # builds a angles tree given the min max angle
        pass

    def makeavgdir(self):
        # create a folder average into the dataset path
        # avg
        #  |- processed_images
        #  |- aligned_images
        #  |- correlation_images
        #  |- results
        #  |- template_rot
        self.avgpath = join(self.path, "avg")
        if not isdir(self.avgpath):
            mkdir(self.avgpath)

        subfolders = [
            "processed_images", "aligned_images", "correlation_images",
            "results", "template_rot"
        ]
        for folder in subfolders:
            self.subfolders[folder] = join(self.avgpath, folder)
            if not isdir(self.subfolders[folder]):
                mkdir(self.subfolders[folder])

    def gather_pictures(self):
        for i, image in enumerate(self.init_imgs):
            self.imgs.set_image(i, image)

    # image operations
    def c2gscale(self):
        for i, img in enumerate(self.imgs):
            img.convert2grayscale()
            self.imgs.set_image(i, img)
        lg.info("dataset converted to grayscale")

    def squareit(self):
        for i, img in enumerate(self.imgs):
            img.squareit()
            self.imgs.set_image(i, img)
        lg.info("dataset squared")

    def transpose(self):
        for i, img in enumerate(self.imgs):
            img.transpose()
            self.imgs.set_image(i, img)
        lg.info("dataset transposed")

    def normalize(self):
        for i, img in enumerate(self.imgs):
            img.normalize()
            self.imgs.set_image(i, img)
        lg.info("dataset normalized")

    def binning(self, n=1):
        for i, img in enumerate(self.imgs):
            img.binning(n)
            self.imgs.set_image(i, img)
        lg.info("dataset binned {0} times".format(n))

    # template handling
    def generate_template(self, option, rot_precision=None):
        if type(option) is str:
            if option == "UseFirstImage":
                self.template = self.imgs.get_image(0)
                self.templateft = ImgFFT(self.template)
                self.templateft.ft()
            elif option == "Average":
                self.average(False)
                self.template = self.avg
                self.templateft = ImgFFT(self.template)
                self.templateft.ft()
            else:
                raise TemplateTypeError(option)
        elif type(option) == MyImage:
            self.template = option
            self.templateft = ImgFFT(self.template)
            self.templateft.ft()
        else:
            raise TemplateTypeError(type(option))
        lg.info("template created: {0}".format(option))

        if type(rot_precision) == tuple:

            print("Creating rotation references")

            # rot_precision format = (from, to, precision)
            frm = rot_precision[0]
            to = rot_precision[1]
            prec = rot_precision[2]
            self.angles_list = np.arange(frm, to, prec)

            print("From", frm, "to", to, "precision", prec)
            print("Total:", len(self.angles_list), "angles")
            self.templaterotsft = NpyFTArray(
                (self.subfolders["template_rot"], "template_rot_ft.npy",
                 len(self.angles_list)))
            for i, angle in enumerate(self.angles_list):
                print("creating angle: ", angle)
                rot = deepcopy(self.template)
                rot.rotate(angle)

                rotft = ImgFFT(rot)
                rotft.ft()

                self.templaterotsft.set_image(i, rotft)

    def align_images(self, debug=False):
        c = 0

        anglestree = AnglesTree(-1, 1, 0.1, self.template)

        for image in self.imgs:

            angle = anglestree.analyze_image(image)

            #            # generate the fourier transform of the image
            #            imgft = ImgFFT(image)
            #            imgft.ft()
            #
            #            # calculate the rotations
            #            smax = 0
            #            idxmax = 0
            #            for idx, temp in enumerate(self.templaterotsft):
            #                corr = temp.correlate(imgft)
            #                s, dx, dy = corr.find_peak(1)
            #
            #                if s > smax:
            #                    smax = s
            #                    idxmax = idx
            #
            #            angle = float(self.angles_list[idxmax])

            print("angle found", angle)

            rotalgimage = deepcopy(image)
            rotalgimage.rotate(-angle)

            # calculate the shifts
            rotalgimageft = ImgFFT(rotalgimage)
            rotalgimageft.ft()

            corr = rotalgimageft.correlate(self.templateft)
            self.corrs.set_image(c, corr)

            dx, dy = corr.find_translation(1)
            self.shifts.append((dx, dy, angle))

            print("shifts:", dx, dy)

            rotalgimage.move(dx, dy)

            self.algimgs.set_image(c, rotalgimage)

            if debug:
                print("Correlated image:", c)

            lg.info("correlated image n: " + str(c))

            c += 1

    def average(self, aligned=True, debug=False):
        if aligned:
            dataset = self.algimgs
        else:
            dataset = self.imgs
        s = MyImage(np.zeros(dataset[0].data.shape))
        for i, picture in enumerate(dataset):
            if debug:
                print("Averaging picture:", i)
            s += picture

        self.avg = s / dataset.n

    # I/O methods
    def get_template_path(self):
        return join(self.avgpath, "template.png")

    def get_avg_path(self):
        return join(self.subfolders["results"], "avg.png")

    def save_template(self):
        self.template.save(join(self.avgpath, "template.png"))

    def load_template(self, filepathname):
        self.template.read_from_file(filepathname)

    def save_avg(self):
        self.avg.save(self.get_avg_path())

    def save_shifts(self):
        with open(join(self.subfolders["results"], "shifts_log.txt"),
                  "w") as f:
            for shift in self.shifts:
                f.write("{0[0]:d} | {0[1]:d} | {0[2]:.3f}\n".format(shift))
        lg.info("Shifts saved")

    def load_shifts(self):
        with open(join(self.subfolders["results"], "shifts_log.txt")) as f:
            lines = f.readlines()

        self.shifts = []
        for line in lines:
            sdata = line.split(' | ')
            sdata = [d.strip() for d in sdata]
            data = [int(sdata[0]), int(sdata[1]), float(sdata[2])]
            print(data)
            self.shifts.append(data)
Example #12
0
class AvgFolder(object):

    # Initialization functions
    def __init__(self, path):
        # define the main path
        self.path = path

        # folder environment variable
        self.names = []
        self.avgpath = ""
        self.subfolders = {}

        # create the folder environment
        try:
            self.makeavgdir()
        except FileNotFoundError as e:
            print("Folder not found")
        except:
            print("WTF")

        # create log file in the avg folder
        lg.basicConfig(filename=join(self.avgpath, 'example.log'),
                       level=lg.INFO)

        # initialize variables
        self.imgs = []
        self.template = MyImage()
        self.templateft = None
        self.angles_list = []
        self.templaterotsft = []

        self.algimgs = []
        self.corrs = []
        self.shifts = []

        self.avg = MyImage()

    def gather_pictures(self):
        # for now gather all the files, next check for picture extensions
        p = self.path
        self.names = [f for f in listdir(p) if isfile(join(p, f))]

        for imgname in self.names:
            path, name, ext = get_pathname(imgname)
            if ext in ['.jpg', '.png']:
                imagepath = join(self.path, imgname)
                img = MyImage()
                img.read_from_file(imagepath)
                self.imgs.append(img)
                lg.info("Image: {0} imported successfully".format(imagepath))

    def makeavgdir(self):
        # create a folder average into the dataset path
        # avg
        #  |- processed_images
        #  |- aligned_images
        #  |- correlation_images
        #  |- results
        self.avgpath = join(self.path, "avg")
        if not isdir(self.avgpath):
            mkdir(self.avgpath)

        subfolders = [
            "processed_images", "aligned_images", "correlation_images",
            "results"
        ]
        for folder in subfolders:
            self.subfolders[folder] = join(self.avgpath, folder)
            if not isdir(self.subfolders[folder]):
                mkdir(self.subfolders[folder])

    # image operations
    def c2gscale(self):
        for img in self.imgs:
            img.convert2grayscale()
        lg.info("dataset converted to grayscale")

    def squareit(self):
        for img in self.imgs:
            img.squareit()
        lg.info("dataset squared")

    def transpose(self):
        for img in self.imgs:
            img.transpose()
        lg.info("dataset transposed")

    def normalize(self):
        for img in self.imgs:
            img.normalize()
        lg.info("dataset normalized")

    def binning(self, n=1):
        for img in self.imgs:
            img.binning(n)
        lg.info("dataset binned {0} times".format(n))

    # template handling
    def generate_template(self, option, rot_precision=None):
        if type(option) is str:
            if option == "UseFirstImage":
                self.template = self.imgs[0]
                self.templateft = ImgFFT(self.template)
                self.templateft.ft()
            elif option == "Average":
                self.average(False)
                self.template = self.avg
                self.templateft = ImgFFT(self.template)
                self.templateft.ft()
            else:
                raise TemplateTypeError(option)
        elif type(option) == MyImage:
            self.template = option
            self.templateft = ImgFFT(self.template)
            self.templateft.ft()
        else:
            raise TemplateTypeError(type(option))
        lg.info("template created: {0}".format(option))

        if type(rot_precision) == tuple:

            print("Creating rotation references")

            # rot_precision format = (from, to, precision)
            frm = rot_precision[0]
            to = rot_precision[1]
            prec = rot_precision[2]
            self.angles_list = np.arange(frm, to, prec)

            print("From", frm, "to", to, "precision", prec)
            print("Total:", len(self.angles_list), "angles")

            for angle in self.angles_list:
                print("creating angle: ", angle)
                rot = deepcopy(self.template)
                rot.rotate(angle)

                rotft = ImgFFT(rot)
                rotft.ft()

                self.templaterotsft.append(rotft)

    def align_images(self, debug=False):
        c = 0
        for image in self.imgs:

            # generate the fourier transform of the image
            imgft = ImgFFT(image)
            imgft.ft()

            # calculate the rotations
            smax = 0
            idxmax = 0
            for idx, temp in enumerate(self.templaterotsft):
                corr = temp.correlate(imgft)
                s, dx, dy = corr.find_peak(1)

                if s > smax:
                    smax = s
                    idxmax = idx

            print("angle found", self.angles_list[idxmax])

            rotalgimage = deepcopy(image)
            rotalgimage.rotate(-self.angles_list[idxmax])

            # calculate the shifts
            rotalgimageft = ImgFFT(rotalgimage)
            rotalgimageft.ft()

            corr = rotalgimageft.correlate(self.templateft)
            self.corrs.append(corr)

            dx, dy = corr.find_translation(1)
            self.shifts.append((dx, dy))

            print("shifts:", dx, dy)

            rotalgimage.move(dx, dy)
            self.algimgs.append(rotalgimage)

            if debug:
                print("Correlated image:", c)
            lg.info("correlated image n: " + str(c))

            c += 1

    def average(self, aligned=True):
        if aligned:
            dataset = self.algimgs
        else:
            dataset = self.imgs
        s = MyImage(np.zeros(dataset[0].data.shape))
        for picture in dataset:
            s += picture

        self.avg = s / len(dataset)

    # I/O methods

    def save_template(self):
        self.template.save(join(self.avgpath, "template.png"))

    def load_template(self, filepathname):
        self.template.read_from_file(filepathname)

    def save_imgs(self):
        for i, img in enumerate(self.imgs):
            filename, ext = splitext(self.names[i])
            img.save(
                join(self.subfolders["processed_images"],
                     "proc_" + filename + ".png"))
        lg.info("processed dataset saved, images {0}".format(i))

    def laod_imgs(self):
        lg.info("Loading processed images")
        p = self.subfolders["processed_images"]
        names = [f for f in listdir(p) if isfile(join(p, f))]

        self.imgs = []
        for name in names:
            img = MyImage()
            img.read_from_file(name)
            self.imgs.append(img)
            lg.info("Image: {0} imported successfully".format(name))

    def save_algimgs(self):
        for i, algimg in enumerate(self.algimgs):
            filename, ext = splitext(self.names[i])
            algimg.save(
                join(self.subfolders["aligned_images"],
                     ("alg_" + filename + ".png")))
        lg.info("aligned dataset saved, images {0}".format(i))

    def laod_algimgs(self):
        lg.info("Loading aligned images")
        p = self.subfolders["aligned_images"]
        names = [f for f in listdir(p) if isfile(join(p, f))]

        self.imgs = []
        for name in names:
            img = MyImage()
            img.read_from_file(name)
            self.imgs.append(img)
            lg.info("Image: {0} imported successfully".format(name))

    def save_corrs(self):
        for i, corr in enumerate(self.corrs):
            filename, ext = splitext(self.names[i])
            corr.save(
                join(self.subfolders["correlation_images"],
                     ("corr_" + filename + ".png")))
        lg.info("correlations dataset saved, images {0}".format(i))

    def laod_corrs(self):
        lg.info("Loading correlation images")
        p = self.subfolders["correlation_images"]
        names = [f for f in listdir(p) if isfile(join(p, f))]

        self.imgs = []
        for name in names:
            img = MyImage()
            img.read_from_file(name)
            self.imgs.append(img)
            lg.info("Image: {0} imported successfully".format(name))

    def save_avg(self):
        self.avg.save(join(self.subfolders["results"], "avg.png"))

    def save_shifts(self):
        with open(join(self.subfolders["results"], "shifts_log.txt"),
                  "w") as f:
            for shift in self.shifts:
                f.write("{0[0]:d} | {0[1]:d}\n".format(shift))
        lg.info("Shifts saved")

    def load_shifts(self):
        with open(join(self.subfolders["results"], "shifts_log.txt")) as f:
            lines = f.readlines()

        self.shifts = []
        for line in lines:
            data = line.split(' - ')
            data = [int(d.strip()) for d in data]
            print(data)
            self.shifts.append(data)
class ImageManager:
    ''' This class manages the images to be elaborated, it works in background 
    of the GUI to provide the transformations needed and the conversion to gif
    '''
    def __init__(self, imagepathname):

        # set the initial path and extract the approriate information
        self.initialpath = imagepathname

        path, name, ext = get_pathname(self.initialpath)
        self.mainpath = path
        self.name = name
        self.inimg_name = self.name + ext

        # create the directory for the elaboration
        self.bufpath = join(self.mainpath, self.name)
        if not isdir(self.bufpath):
            mkdir(self.bufpath)

        # open the source image
        self.inimage = ImagePath(self.name, MyImage(), self.bufpath)

        # declare the fourier transform
        self.ftimage = 0

        # TODO
        # findppeak on the better cc
        # represent it with the tkinter canvas

    def init_inimage(self):
        # open the source image
        self.inimage = ImagePath(self.name, MyImage(), self.bufpath)
        self.inimage.image.read_from_file(self.initialpath)
        self.inimage.image.convert2grayscale()
        self.inimage.image.squareit()

        # resize the image and save it in gif format
        self.savegif(self.inimage, (500, 500))

    def calculate_bandpass(self, inradius, insmooth, outradius, outsmooth):
        ''' This method calculates the filter and saves the corresponding images
        the power spectrum (self.psimage) and the result of the filter
        (self.iftimage) in the temp folder
        '''

        #transfrom the image
        self.ftimage = ImgFFT(self.inimage.image)
        self.ftimage.ft()

        # create bandpass mask
        mask = Mask(self.inimage.image.data.shape)
        mask.bandpass(inradius, insmooth, outradius, outsmooth)
        self.ftimage.apply_mask(mask)

        # represent the masked ps
        self.ftimage.power_spectrum()
        self.psimage = ImagePath(self.name + "_ps", self.ftimage.ps,
                                 self.bufpath)
        self.savegif(self.psimage, (500, 500))

        # calculate inverse transform
        self.ftimage.ift()
        self.iftimage = ImagePath(self.name + "ift", self.ftimage.imgifft,
                                  self.bufpath)
        self.savegif(self.iftimage, (500, 500))

    def savegif(self, imagepath, size):
        ''' Given a class imagepath and the size of the images, saves into the
        temp folder the associated image
        '''

        # calculate ft for resizing
        imft = ImgFFT(imagepath.image.data)
        imft.ft()
        im = imft.resize_image(size[0], size[1])

        # save resized image
        imsave(imagepath.gifname, im.data, format="gif")

    def rm(self):
        ''' cleans up the buffer folder containing the gifs files'''
        if isdir(self.bufpath):
            rmtree(self.bufpath)