示例#1
0
    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 __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")

        # 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 laod_corrs(self):
        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)
示例#4
0
 def get_phases(self):
     sizeimg = np.real(self.imgfft).shape
     mag = np.zeros(sizeimg)
     for x in range(sizeimg[0]):
         for y in range(sizeimg[1]):
             mag[x][y] = np.arctan2(np.real(self.imgfft[x][y]),
                                    np.imag(self.imgfft[x][y]))
     rpic = MyImage(mag)
     rpic.limit(1)
     return rpic
示例#5
0
 def get_magnitude(self):
     sizeimg = np.real(self.imgfft).shape
     mag = np.zeros(sizeimg)
     for x in range(sizeimg[0]):
         for y in range(sizeimg[1]):
             mag[x][y] = np.sqrt(
                 np.real(self.imgfft[x][y])**2 +
                 np.imag(self.imgfft[x][y])**2)
     rpic = MyImage(mag)
     rpic.limit(1)
     return rpic
示例#6
0
    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 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)
示例#8
0
    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 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))
示例#10
0
    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)
示例#11
0
    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
示例#12
0
    def power_spectrum(self):
        absolutefft = np.abs(self.imgfft)
        xlen = absolutefft.shape[0]
        ylen = absolutefft.shape[1]
        squareftt = deepcopy(absolutefft)
        for i in range(xlen):
            for j in range(ylen):
                if squareftt[i][j] != 0:
                    squareftt[i][j] = np.log(squareftt[i][j])**2
        realpart = np.real(squareftt)
        ps = MyImage(realpart)

        return ps
示例#13
0
    def get_polar_t(self):
        mag = self.get_magnitude()
        sizeimg = np.real(self.imgfft).shape

        pol = np.zeros(sizeimg)
        for x in range(sizeimg[0]):
            for y in range(sizeimg[1]):
                my = y - sizeimg[1] / 2
                mx = x - sizeimg[0] / 2
                if mx != 0:
                    phi = np.arctan(my / float(mx))
                else:
                    phi = 0
                r = np.sqrt(mx**2 + my**2)

                ix = map_range(phi, -np.pi, np.pi, sizeimg[0], 0)
                iy = map_range(r, 0, sizeimg[0], 0, sizeimg[1])

                if ix >= 0 and ix < sizeimg[0] and iy >= 0 and iy < sizeimg[1]:
                    pol[x][y] = mag.data[int(ix)][int(iy)]
        pol = MyImage(pol)
        pol.limit(1)
        return pol
    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
示例#15
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")
示例#16
0
def run_create_test_dataset(folder):
    debug_mode = True

    # set parameters
    testdatasetpath = folder
    mypicname = "./data/Lenna.png"

    n_pictures = 25
    min_a = -10
    max_a = 10
    min_xs = -25
    max_xs = 25
    min_ys = -25
    max_ys = 25
    flip_angle = True

    mylog = Logger("Create gray dataset",
                   testdatasetpath + "main_logfile.txt",
                   debug_mode=debug_mode)

    mylog.log("Creating dataset in:\n" + testdatasetpath)
    mylog.log("Using the picture: " + mypicname)

    mylog.log("Creating dataset with {0} pictures".format(n_pictures))
    mylog.log("With rotations from {0} to {1} degree".format(min_a, max_a))
    mylog.log("With shift in x: from {0} to {1} and y: from {2} to {3}".format(
        min_xs, max_xs, min_ys, max_ys))
    mylog.log(
        "The dataset will be generated by {0} randomly flipping rotations and translations"
        .format("" if flip_angle == True else "not"))

    if not isdir(testdatasetpath):
        mkdir(testdatasetpath)
        mylog.log("Created test dataset path")

    # create a test dataset:

    mypic = MyImage(mypicname)
    mypic.squareit()
    mypic.convert2grayscale()
    mypic.binning(2)
    mypic.normalize()

    mylog.log("Processing done")

    template_folder = join(testdatasetpath, "template_folder")

    if not isdir(template_folder):
        mkdir(template_folder)

    mypic.save(join(template_folder, "template.png"))
    mylog.log("Saved the original image in the template folder")

    if debug_mode:
        mypic.show_image()
        plt.show()

    mylog.log(
        "------------------------------\nCreating dataset\n------------------------------"
    )

    np.random.seed(10)

    logpathdir = join(testdatasetpath, "tlog")
    if not isdir(logpathdir):
        mkdir(logpathdir)

    with open(join(logpathdir, "mytransformations.log"), 'w') as f:
        angles = np.random.uniform(min_a, max_a, n_pictures)
        for i in range(n_pictures):
            image = deepcopy(mypic)
            if flip_angle:
                anglefirst = False if np.random.randint(0, 2) == 0 else True
            else:
                anglefirst = True

            angle = angles[i]
            dx = np.random.randint(min_xs, max_xs)
            dy = np.random.randint(min_ys, max_ys)

            f.write("{0} {1} {2} {3}\n".format(anglefirst, dx, dy, angle))
            mylog.log(
                "Pictrue with: rot first {0}, angle: {1}, shift x: {2}, y: {3} created"
                .format(anglefirst, angle, dx, dy))

            if anglefirst:
                image.rotate(angle)
                image.move(dx, dy)
            else:
                image.move(dx, dy)
                image.rotate(angle)

            if debug_mode:
                image.show_image()
                plt.show()

            image.save(join(testdatasetpath, "pic_" + str(i) + ".png"))
示例#17
0
def run_average_gray(folder):
    # options
    debug_mode = True

    # chose path to image sequence folder
    datasetpath = folder

    memsave = True  # True | False

    preprocop = [("convert to grayscale", ), ("square it", ), ("binning", 0),
                 ("transpose", ), ("normalize", )]

    custom_template = False  # True | False
    template_image_path = folder + "template_folder/template.png"  # path to image

    auto_template_type = "UseFirstImage"  # "Use First Image" | "Average"
    save_template = True  # True | False

    align_images = True  # True | False
    align_mode = "fixed"  # "fixed | tree" // fixed still fastest option
    align_space = (-1, 1, 0.1)  # (min angle, max angle, precision)

    # logger
    mylog = Logger("Averaging Gray",
                   datasetpath + "main_logfile.txt",
                   debug_mode=debug_mode)

    mylog.log("Debug mode: " + "ON" if debug_mode == True else "OFF")
    mylog.log("For the folder:")
    mylog.log(datasetpath)
    mylog.log("Averaging type: grey")
    mylog.log("Memory saving mode: " + str(memsave))

    mylog.log(
        "------------------------------\nLoading dataset\n------------------------------"
    )
    if memsave:
        avg = AvgFolderMem(datasetpath)
    else:
        avg = AvgFolder(datasetpath)

    avg.gather_pictures()
    # build the informatiosn
    mylog.log("number of pictures:" + str(avg.init_imgs.n))
    image = avg.init_imgs.get_image(0)
    mylog.log("Size of images: " + str(image.data.shape[0]) + "x" +
              str(image.data.shape[1]))

    mylog.log("--- Start preporcessing ---", True)

    nametofunc = {}
    nametofunc[preprocop[0]] = lambda: avg.c2gscale()
    nametofunc[preprocop[1]] = lambda: avg.squareit()
    nametofunc[preprocop[2]] = lambda n: avg.binning(n)
    nametofunc[preprocop[3]] = lambda: avg.transpose()
    nametofunc[preprocop[4]] = lambda: avg.normalize()

    for name in preprocop:
        if len(name) == 1:
            nametofunc[name]()
            mylog.log("Process: " + name[0])
        if len(name) == 2:
            nametofunc[name](name[1])
            mylog.log("Process: " + name[0] + "Arguments: " + str(name[1]))
    mylog.log("Processing took: ", True)

    mylog.log(
        "------------------------------\nGenerating template\n------------------------------"
    )

    if custom_template:
        custom_t = MyImage(template_image_path)
        custom_t.convert2grayscale()
        mylog.log("Template loaded from: " + template_image_path)
        mylog.log("Template image is: {0}x{1}".format(custom_t.get_sizex(),
                                                      custom_t.get_sizey()))
        avg.generate_template(custom_t)
    else:
        avg.generate_template(auto_template_type)
        mylog.log("Template generated: " + auto_template_type)

    mylog.log("Template generated", True)

    if save_template:
        avg.save_template()

    if debug_mode:
        avg.template.show_image()
        plt.show()
        avg.template.inspect()

    if align_images:
        mylog.log(
            "------------------------------\nAlignment\n------------------------------"
        )
        mylog.log("Choosen Aligment: " + align_mode)
        alignnames = ["min angle: ", " |max angle: ", " |precision: "]
        mylog.log("".join(a + str(d) for a, d in zip(alignnames, align_space)))
        avg.align_images(align_mode, align_space, debug_mode)
        avg.save_shifts()

        mylog.log("Alignment done", True)
        if avg.anglestree != None:
            mylog.log("Numnber of template generated: " +
                      str(len(avg.anglestree.angles_nodes)))
            mylog.log("Normally would be: " + str(
                len(np.arange(align_space[0], align_space[1], align_space[2])))
                      )
        else:
            mylog.log("Numnber of template generated: " +
                      str(avg.templaterotsft.n))
        mylog.log("Shifts saved")

        mylog.log(
            "------------------------------\nAverage\n------------------------------"
        )
        avg.average(debug=debug_mode)
        avg.save_avg()
        mylog.log("Average Complete", True)

        if debug_mode:
            avg.avg.show_image()
            plt.show()
            avg.avg.inspect()

    mylog.log("End procedure", True)
示例#18
0
 def ift(self):
     self.imgifft = MyImage(np.real(fft.ifft2(fft.fftshift(self.imgfft))))
示例#19
0
    from matplotlib import pyplot as plt

    # load sample image
    imagepath = "C:/Users/Mauro/Desktop/Vita Online/Programming/Picture cross corr/Lenna.png"
    imagepath = "C:/Users/Mauro/Desktop/Vita Online/Programming/Picture cross corr/silentcam/dataset24/avg/correlation_images/corr_1497777846958.png"

    imagepath = "../../../Lenna.png"

    #    # convert range test
    #    x = np.arange(0, 3, 0.1)
    #    print(x)
    #
    #    for i in x:
    #        print(i, map_range(i, 0, 1, 0, 2*np.pi))

    im = MyImage()
    im.read_from_file(imagepath)
    im.convert2grayscale()

    print("Original image")
    im.show_image()
    plt.show()

    ft = ImgFFT(im)
    ft.ft()

    imres = ft.resize_image(256, 256)
    imres.show_image()
    plt.show()

#    print("Power Spectrum")
示例#20
0
 def get_real_part(self):
     r = MyImage(np.real(self.imgfft))
     r.limit(1)
     return r
示例#21
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)
示例#22
0
 def get_image(self, i):
     with open(self.paths[i], 'rb') as f:
         imgfft = np.load(f)
         ft = ImgFFT(MyImage())
         ft.imgfft = imgfft
     return ft
示例#23
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)
示例#24
0
 def get_image(self, i):
     with open(self.paths[i], 'rb') as f:
         data = np.load(f)
     return MyImage(data)
示例#25
0
 def get_image(self, i):
     path = self.paths[i]
     image = MyImage(path)
     return image
示例#26
0
 def get_imag_part(self):
     r = MyImage(np.imag(self.imgfft))
     r.limit(1)
     return r
示例#27
0
 def ift(self):
     return MyImage(np.real(fft.ifft2(fft.fftshift(self.ft))))
 def get_channel(self, channel):
     if type(channel) == str:
         c2idx = {'r': 0, 'g': 1, 'b': 2}
     else:
         c2idx = [0, 1, 2]
     return MyImage(self.data[:, :, c2idx[channel]])