Ejemplo n.º 1
0
Archivo: Hog.py Proyecto: tladyman/HOG
    def __init__(self, filename, blockSizeX, blockSizeY, overlap, cellSizeX, cellSizeY, oBins):
        """Constructor from an input image.

        Args:
            filename: Filename of input image e.g. 'test.png'.
                It can also takes a numpy array
            blockSizeX: The number of cells on the x axis of the Blocks. The
                size in pixels is blockSizeX*cellSizeX
            blockSizeY: The number of cells on the y axis of the Blocks. The
                size in pixels is blockSizeY*cellSizeY
            overlap: Fraction of overlap between Blocks.
            cellSizeX: The number of pixels on the x axis of the Cells within
                this Block.
            cellSizeY: The number of pixels on the y axis of the Cells within
                this Block.
            oBins: Number of orientation bins

        """
        if type(filename) == str:
            # load the image
            self._inputImage = misc.imread(filename)
        elif type(filename) == np.ndarray:
            self._inputImage = filename
        else:
            raise TypeError("That is not a valid input")

        # plt.imshow(self._inputImage, cmap=plt.cm.gray, interpolation="nearest")
        # plt.show()

        # Calculate gradient and magnitude arrays and then create Blocks for each of them
        gx, gy = self._create_gradient_images(self._inputImage)

        # Create block objects for each the magnitude and gradient images.
        self.gradBlock = Block(self.grad, blockSizeX, blockSizeY, overlap, cellSizeX, cellSizeY)
        self.magBlock = Block(self.mag, blockSizeX, blockSizeY, overlap, cellSizeX, cellSizeY)

        # Create histogram object - which takes the gradient Block object and the
        # magnitude Block object
        self.histogram = Histogram(self.gradBlock, self.magBlock, oBins)

        self.output = self.histogram.histArray

        # Draw an output
        self.histogramPlotter = HistogramPlotter(self._inputImage, self.output)
        self.histogramPlotter.plot()
Ejemplo n.º 2
0
def main():

    # build a simple dummy analysis to test the composition of Morphisms
    ana = Analysis("ana")
    ana_t = Analysis("ana_t")

    m0 = DummyMorphism("m0") # always put a dummy morphism at the beginning
    m1 = ExpGeneratorMorphism("m1", pars = {"scale": 1.0})
    m2 = ConvMorphism("m2", pars = {"loc": 1.0, "scale": 1.6}, kern = np.random.normal)
    m3 = TransfMorphism("m3", transf = lambda x: x - 0.05 * x**2 + 0.01 * x**3)
    m4 = DummyMorphism("m4")
    m5 = DummyMorphism("m5")

    # this is the modified morphism
    m1_t = ExpGeneratorMorphism("m1_t", pars = {"scale": 2.0})
    
    ana.add_morphisms([m0, m1, m2, m3, m4, m5])
    ana_t.add_morphisms([m0, m1_t, m2, m3, m4, m5])

    nsamp = 1000000
    dummy_data = pd.DataFrame.from_dict({"datacol": np.random.rand(nsamp)})
    
    # run both analyses on the same data
    out = ana.run(dummy_data)
    out_t = ana_t.run(dummy_data)

    # compute the resulting distributions
    binning = np.linspace(-2, 20, 30)
    hist = Histogram.from_data(name = r'$p(x_3|\theta_1,\theta_2,\theta_3)$', data = out, binning = binning)
    hist_t = Histogram.from_data(name = r'$p(x_3|\tilde{\theta_1},\theta_2,\theta_3)$', data = out_t, binning = binning)

    # play a bit with the likelihood ratio that should be propagated
    source_hist = Histogram.from_data(r'$p(x_1|\theta_1)$', data = m1(dummy_data), binning = binning)
    source_hist_t = Histogram.from_data(r'$p(x_1|\tilde{\theta_1})$', data = m1_t(dummy_data), binning = binning)
    HistogramPlotter.plot_histograms([source_hist, source_hist_t], color = ["black", "salmon"], outfile = "/home/philipp/OX/thesis/FastProp/run/source.pdf", xlabel = r'$x_1$', ylabel = "events")
    
    # also get the weights and compare the result
    # first, create the profile of this analysis
    prof = Profiler(ana)
    prof.profile(dummy_data)
    
    est = HistogramLREstimator(nbins = 30)
    est.build_estimate(data_num = m1_t(dummy_data), data_den = m1(dummy_data))
    
    prop = Propagator("prop")
    prop.generate_propagator("m1", "m5", prof, est)    
    hist_rw = HistogramReweighter.reweight_to(hist, prop)
    hist_rw.name = r'$p(x_3|\theta_1,\theta_2,\theta_3)\cdot R(x_3; \tilde{\theta_1}, \theta_1)$'

    # plot the final histograms
    HistogramPlotter.plot_histograms([hist, hist_t, hist_rw], show_ratio = True, color = ["black", "salmon", "mediumseagreen"], ratio_reference = hist_t, xlabel = r'$x_3$', ylabel = "events", outfile = "/home/philipp/OX/thesis/FastProp/run/target_rw.pdf")
    HistogramPlotter.plot_histograms([hist, hist_t], show_ratio = True, color = ["black", "salmon"], ratio_reference = hist_t, xlabel = r'$x_3$', ylabel = "events", outfile = "/home/philipp/OX/thesis/FastProp/run/target.pdf")

    # plot both the original reweighting factor, and the final one
    finebinning = np.linspace(-2, 10, 300)
    finebinning = np.expand_dims(finebinning, axis = 1)
    source_reweighting = est.evaluate(finebinning)
    target_reweighting = prop.predict(finebinning)

    FunctionPlotter.plot_function(finebinning, source_reweighting, outfile = "/home/philipp/OX/thesis/FastProp/run/source_reweighting.pdf", xlabel = r'$x_1$', ylabel = r'$R(x_1; \tilde{\theta_1}, \theta_1)$', color = "black")
    FunctionPlotter.plot_function(finebinning, target_reweighting, outfile = "/home/philipp/OX/thesis/FastProp/run/target_reweighting.pdf", xlabel = r'$x_3$', ylabel = r'$R(x_3; \tilde{\theta_1}, \theta_1)$', color = "black")
Ejemplo n.º 3
0
Archivo: Hog.py Proyecto: tladyman/HOG
class Hog:
    """A container object to manage the HOG algorithm.

    Attributes:
        _inputImage (numpy.ndarray): The raw unprocessed input image.
        grad
        mag
        gradBlock
        magBlock
    """

    def __init__(self, filename, blockSizeX, blockSizeY, overlap, cellSizeX, cellSizeY, oBins):
        """Constructor from an input image.

        Args:
            filename: Filename of input image e.g. 'test.png'.
                It can also takes a numpy array
            blockSizeX: The number of cells on the x axis of the Blocks. The
                size in pixels is blockSizeX*cellSizeX
            blockSizeY: The number of cells on the y axis of the Blocks. The
                size in pixels is blockSizeY*cellSizeY
            overlap: Fraction of overlap between Blocks.
            cellSizeX: The number of pixels on the x axis of the Cells within
                this Block.
            cellSizeY: The number of pixels on the y axis of the Cells within
                this Block.
            oBins: Number of orientation bins

        """
        if type(filename) == str:
            # load the image
            self._inputImage = misc.imread(filename)
        elif type(filename) == np.ndarray:
            self._inputImage = filename
        else:
            raise TypeError("That is not a valid input")

        # plt.imshow(self._inputImage, cmap=plt.cm.gray, interpolation="nearest")
        # plt.show()

        # Calculate gradient and magnitude arrays and then create Blocks for each of them
        gx, gy = self._create_gradient_images(self._inputImage)

        # Create block objects for each the magnitude and gradient images.
        self.gradBlock = Block(self.grad, blockSizeX, blockSizeY, overlap, cellSizeX, cellSizeY)
        self.magBlock = Block(self.mag, blockSizeX, blockSizeY, overlap, cellSizeX, cellSizeY)

        # Create histogram object - which takes the gradient Block object and the
        # magnitude Block object
        self.histogram = Histogram(self.gradBlock, self.magBlock, oBins)

        self.output = self.histogram.histArray

        # Draw an output
        self.histogramPlotter = HistogramPlotter(self._inputImage, self.output)
        self.histogramPlotter.plot()


    def _create_gradient_images(self,pixelArray):
        """Creates gradient images in x and y directions.

        Args:
            pixelArray: The array of pixels

        Returns:
            grad: gradient image
            mag: gradient in the y direction
        """

        # Create the column and row vectors to convolve

        ker = np.array([1,0,-1])

        column = ker.reshape((3,1))
        row = ker.reshape((1,3))

        # mode = constant ensures that the edges of the image ar padded with
        # constant values in this case the default is 0 - perfect for our purposes.
        # The array is then restored to its original dimensions.

        # Convolve the vectors to create gradients in x and y directions
        #TODO: for colour images: np.array([row, row, row])
        gx = ndimage.filters.convolve(pixelArray, row, mode = "constant")
        gy = ndimage.filters.convolve(pixelArray, column, mode = "constant")

        # Create gradient image using arctan2 (remember its in radians!)
        self.grad = np.arctan2(gy,gx)

        # The square of each element is just matrix^2 in python
        self.mag = np.sqrt(gx**2 + gy**2)

        return gx, gy
Ejemplo n.º 4
0
import numpy as np
import matplotlib.pyplot as plt
from scipy import ndimage
from scipy import misc

from HistogramPlotter import HistogramPlotter

img = np.zeros((100, 100), dtype=np.uint8)
histogram = np.zeros((200, 100, 9), dtype=np.uint8)

plotter = HistogramPlotter(img, histogram)

plotter.drawLine(50,50,30, 48, 1)

plt.imshow(plotter.getOutput(), cmap=plt.cm.gray, interpolation="nearest")
plt.show()