Example #1
0
 def __init__(self):
     pygame.sprite.Sprite.__init__(self)
     self.image = load_image('timeout.png')
     self.rect = self.image.get_rect()
     self.x =  int(pygame.display.Info().current_w /2) - NOTE_HALF_X
     self.y =  int(pygame.display.Info().current_h /3) - NOTE_HALF_Y
     self.rect.topleft = self.x, self.y
Example #2
0
def main():
    global SET_RUN_MODE

    if len(sys.argv) != 2:
        print('Usage: <mode>')
        sys.exit(-1)
    else:
        if sys.argv[1] == 'IMAGE':
            SET_RUN_MODE = RUN_MODE.IMAGE
        elif sys.argv[1] == 'POINTS':
            SET_RUN_MODE = RUN_MODE.POINTS
        else:
            print('Available modes:')
            for el in RUN_MODE:
                print(str(el).split('.')[1])
            sys.exit(-1)

    file_dir = os.path.dirname(os.path.realpath('__file__'))

    file_name = ''
    if settings.SOURCE_FILE is not None:
        file_name = settings.SOURCE_FILE
    else:
        file_name = 'data_%s.txt' % time.strftime("%Y%m%d-%H%M%S")

    if SET_RUN_MODE == RUN_MODE.POINTS:
        gen_data.generate_file(settings.NUMBER_OF_POINTS, settings.DIMENSION,
                               file_name)

    data_dir_path = os.path.join(file_dir, 'data')
    print(data_dir_path)

    width, height = 0, 0
    if SET_RUN_MODE == RUN_MODE.IMAGE:
        source_image_name = settings.SOURCE_IMAGE_NAME
        width, height = image_loader.load_image(
            os.path.join(data_dir_path, source_image_name), file_name)

    data = np.transpose(
        np.loadtxt(os.path.join(data_dir_path, file_name),
                   unpack=True,
                   delimiter=',',
                   dtype=int))

    k = settings.K

    initial_centroids = helpers.init_centroids(data, k)

    print('Initialized centroids')
    for el in initial_centroids:
        print(el)

    centroids, idx = run(data, initial_centroids)

    print('Final centroids')
    for el in centroids:
        print(el)

    if SET_RUN_MODE == RUN_MODE.IMAGE:
        helpers.draw_image(idx, centroids, width, height)
Example #3
0
 def __init__(self):
     pygame.sprite.Sprite.__init__(self)
     self.image = load_image('timeout.png')
     self.rect = self.image.get_rect()
     self.x = int(pygame.display.Info().current_w / 2) - NOTE_HALF_X
     self.y = int(pygame.display.Info().current_h / 3) - NOTE_HALF_Y
     self.rect.topleft = self.x, self.y
Example #4
0
def viewTif():
    from image_loader import load_image
    filepath = '/home/b_mehta/monHiTp/test180420/k3_012918_1_24x24_t45b_0357.tif'

    imArray = load_image(filepath)
    plt.figure()
    plt.imshow(imArray)
    plt.savefig('/home/b_mehta/monHiTp/test180420/test.png')
def test_load():
    filename = pth.join('.', 'test_data', 'blurry_ring.png')
    test_on_image = il.load_image(filename)
    obs_size = (200, 200)
    #obs_max = 
    #obs_min =

    exp_size = test_on_image.shape
    #exp_max =
    #exp_min =

    assert ((obs_size == exp_size))# and (obs_max == exp_max) and (obs_min == exp_min))
Example #6
0
 def test_file(self, files):
     """Tests if input image has appropriate size and contains data"""
     for f in files:
         try:
             im = load_image(f, 0)
         except ValueError:
             QMessageBox.critical(self, "Error", "Could not load file")
             return False
         if not im.shape == self.pc.mask.shape:
             QMessageBox.critical(self, "Error",
                                  "Loaded image has wrong size")
             return False
     return True
def plot_test_image_and_edges():
    """
    example to plot an image and the detected edges
    """
    test_file = pth.join(".", "tests", "test_data", "10_circles_colour.gif")
    image_in = load_image(test_file)
    edges = detect_edge(image_in)
    fig, axes = plt.subplots(nrows=1, ncols=2)
    ax_orig = axes[0]
    ax_edges = axes[1]
    ax_orig.imshow(image_in)
    ax_edges.imshow(edges)
    fig.show()
Example #8
0
 def __init__(self):
     pygame.sprite.Sprite.__init__(self)
     self.image = load_image('player.png')
     self.rect = self.image.get_rect()
     self.image_orig = self.image
     self.screen = pygame.display.get_surface()
     self.area = self.screen.get_rect()
     CENTER_X = int(pygame.display.Info().current_w / 2)
     CENTER_Y = int(pygame.display.Info().current_h / 2)
     self.x = CENTER_X
     self.y = CENTER_Y
     self.rect.topleft = self.x, self.y
     self.x, self.y = findspawn()
     self.dir = 0
     self.speed = 0.0
     self.maxspeed = 21.5
     self.minspeed = -1.85
     self.acceleration = 0.095
     self.deacceleration = 0.12
     self.softening = 0.04
     self.steering = 1.60
Example #9
0
 def __init__(self):
     pygame.sprite.Sprite.__init__(self)
     self.image = load_image('player.png')
     self.rect = self.image.get_rect()
     self.image_orig = self.image
     self.screen = pygame.display.get_surface()
     self.area = self.screen.get_rect()
     CENTER_X =  int(pygame.display.Info().current_w /2)
     CENTER_Y =  int(pygame.display.Info().current_h /2)
     self.x = CENTER_X
     self.y = CENTER_Y
     self.rect.topleft = self.x, self.y
     self.x, self.y = findspawn()
     self.dir = 0
     self.speed = 0.0
     self.maxspeed = 21.5
     self.minspeed = -1.85
     self.acceleration = 0.095
     self.deacceleration = 0.12
     self.softening = 0.04
     self.steering = 1.60
def predict(image_path, checkpoint_path, topk, is_gpu_available):
    image = load_image(image_path)
    model = load_model(checkpoint_path)
    [model] = to_cuda_when_available([model], is_gpu_available)

    with torch.no_grad():
        [image] = to_cuda_when_available([image.unsqueeze(0)],
                                         is_gpu_available)
        model.eval()
        output = model.forward(image)
        probabilities = torch.exp(output)

        top_k_probabilities, top_k_index = torch.topk(probabilities, topk)

        index_to_class = {
            value: key
            for key, value in model.class_to_idx.items()
        }

        top_k_classes = list(
            map(lambda index: index_to_class[index],
                np.array(top_k_index.cpu())[0]))
    return top_k_probabilities, top_k_classes
Example #11
0
def on_the_fly(folder_path,
               base_filename,
               index,
               last_scan,
               calibration_file,
               PP,
               pixelSize,
               num_of_smpls_per_row,
               extract_Imax_Iave_ratio_module,
               extract_texture_module,
               extract_signal_to_noise_module,
               extract_neighbor_distance_module,
               add_feature_to_csv_module,
               attribute1=[['scan#', 'Imax', 'Iave', 'Imax/Iave']],
               attribute2=[['scan#', 'texture_sum']],
               attribute3=[['scan#', 'peak_num']],
               attribute4=[['scan#', 'neighbor_distance']],
               attribute5=[['scan#', 'SNR']]):
    """
    run when starting to collect XRD images, and finish when finishing measuring the whole library
    """
    # generate a folder to put processed files
    save_path = os.path.join(folder_path, 'Processed')
    if not os.path.exists(save_path):
        os.makedirs(save_path)

    # initializing parameters, transform the calibration parameters from WxDiff to Fit2D
    d_in_pixel, Rotation_angle, tilt_angle, lamda, x0, y0 = parse_calib(
        calibration_file)
    Rot = (np.pi * 2 - Rotation_angle) / (2 * np.pi) * 360  # detector rotation
    tilt = tilt_angle / (2 * np.pi) * 360  # detector tilt  # wavelength
    d = d_in_pixel * pixelSize * 0.001  # measured in milimeters

    # generate a random series of numbers, in case restart the measurement from the middle, the new master file will not overwrite the previous one
    master_index = str(int(random.random() * 100000000))

    while (index <= last_scan):
        imageFilename = base_filename + file_index(index) + '.tif'
        imageFullname = os.path.join(folder_path, imageFilename)
        print("\r")
        # wait until an image is created, and process the previous image, to avoid crashing
        print 'waiting for image', imageFullname + ' to be created...'
        print("\r")
        sleep = 0
        while not os.path.exists(imageFullname) and sleep < 1000:
            time.sleep(1)
            sleep += 1
            # print 'sleeping'
        if sleep == 1000:
            sys.exit()
        print 'processing image ' + imageFullname
        print("\r")
        while (1):
            try:
                # import image and convert it into an array
                imArray = load_image(imageFullname)

                # data_reduction to generate Q-chi and 1D spectra, Q
                Q, chi, cake, Qlist, IntAve = data_reduction(
                    imArray, d, Rot, tilt, lamda, x0, y0, PP, pixelSize)

                # save Qchi as a plot *.png and *.mat
                save_Qchi(Q, chi, cake, imageFilename, save_path)
                # save 1D spectra as a *.csv
                save_1Dcsv(Qlist, IntAve, imageFilename, save_path)
                # extract composition information if the information is available
                # extract the number of peaks in 1D spectra as attribute3 by default
                newRow3, peaks = extract_peak_num(Qlist, IntAve, index)
                attribute3.append(newRow3)
                attributes = np.array(attribute3)

                # save 1D plot with detected peaks shown in the plot
                save_1Dplot(Qlist, IntAve, peaks, imageFilename, save_path)

                if extract_Imax_Iave_ratio_module == 'on':
                    # extract maximum/average intensity from 1D spectra as attribute1
                    newRow1 = extract_max_ave_intensity(IntAve, index)
                    attribute1.append(newRow1)
                    attributes = np.concatenate((attribute1, attributes),
                                                axis=1)

                if extract_texture_module == 'on':
                    # save 1D texture spectra as a plot (*.png) and *.csv
                    Qlist_texture, texture = save_texture_plot_csv(
                        Q, chi, cake, imageFilename, save_path)
                    # extract texture square sum from the 1D texture spectra as attribute2
                    newRow2 = extract_texture_extent(Qlist_texture, texture,
                                                     index)
                    attribute2.append(newRow2)
                    attributes = np.concatenate((attribute2, attributes),
                                                axis=1)

                if extract_neighbor_distance_module == 'on':
                    # extract neighbor distances as attribute4
                    newRow4 = nearst_neighbor_distance(index, Qlist, IntAve,
                                                       folder_path, save_path,
                                                       base_filename,
                                                       num_of_smpls_per_row)
                    attribute4.append(newRow4)
                    attributes = np.concatenate((attribute4, attributes),
                                                axis=1)

                if extract_signal_to_noise_module == 'on':
                    # extract signal-to-noise ratio
                    newRow5 = extract_SNR(index, IntAve)
                    attribute5.append(newRow5)
                    attributes = np.concatenate((attribute5, attributes),
                                                axis=1)

                if add_feature_to_csv_module == 'on':
                    # add features (floats) to master metadata
                    # print attributes.shape
                    add_feature_to_master(attributes, base_filename,
                                          folder_path, save_path, master_index,
                                          index)

                break
            except (OSError, IOError, IndexError):
                # The image was being created but not complete yet
                print 'waiting for image', imageFullname + ' to be ready...'
                time.sleep(1)
                sleep += 1
        index += 1  # next file
Example #12
0
from image_loader import load_image
from style_transfer import run_style_transfer
from load_vgg19 import cnn
import torch
from PIL import Image
import matplotlib.pyplot as plt
import torchvision.transforms as transforms
import os

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

cnn_normalization_mean = torch.tensor([0.485, 0.456, 0.406]).to(device)
cnn_normalization_std = torch.tensor([0.229, 0.224, 0.225]).to(device)

unloader = transforms.ToPILImage()

style_img = load_image("./images/style.jpg")
content_img = load_image("./images/content.jpg")

input_img = content_img.clone()

output = run_style_transfer(cnn, cnn_normalization_mean, cnn_normalization_std,
                            content_img, style_img, input_img)

image = output.cpu().clone()  # we clone the tensor to not do changes on it
image = image.squeeze(0)  # remove the fake batch dimension
image = unloader(image)
os.chdir('output')
image.save("output.png")
    def beginReduction(self, pathname):
        '''
        Processing script, reducing images to 1D plots (Q-Chi, Texture, etc)
        '''
        print('\n')
        print(
            '******************************************** Begin image reduction...'
        )
        # PP: beam polarization, according to beamline setup.
        # Contact beamline scientist for this number
        pixelSize = 79  # detector pixel size, measured in microns

        # pathname was imageFullName
        folder_path = os.path.dirname(pathname)
        filename = os.path.basename(pathname)
        # fileRoot was imageFilename
        fileRoot, ext = os.path.splitext(filename)
        index = re.match('.*?([0-9]+).[a-zA-Z]+$', filename).group(1)
        base_filename = re.match('(.*?)[0-9]+.[a-zA-Z]+$',
                                 filename).group(1)  # name w/o ind

        # Master CSV path
        masterPath = os.path.join(folder_path, base_filename + 'master.csv')

        # generate a folder to put processed files
        save_path = os.path.join(self.processedPath, 'Processed')
        if not os.path.exists(save_path):
            os.makedirs(save_path)
        # make master index (vestigial)
        master_index = str(int(random.random() * 100000000))

        attDict = dict.fromkeys([
            'scanNo', 'SNR', 'textureSum', 'Imax', 'Iave', 'I_ratio',
            'numPeaks'
        ])

        ###### BEGIN READING CALIB FILE #################################################
        # initializing params, transform the calibration parameters from WxDiff to Fit2D
        d_in_pixel = float(str(self.detectorData[0]))
        Rotation_angle = float(str(self.detectorData[1]))
        tilt_angle = float(str(self.detectorData[2]))
        lamda = float(str(self.detectorData[3]))
        x0 = float(str(self.detectorData[4]))
        y0 = float(str(self.detectorData[5]))
        #d_in_pixel, Rotation_angle, tilt_angle, lamda, x0, y0 = parse_calib(calibPath)
        Rot = (np.pi * 2 - Rotation_angle) / (2 *
                                              np.pi) * 360  # detector rotation
        tilt = tilt_angle / (2 * np.pi) * 360  # detector tilt  # wavelength
        d = d_in_pixel * pixelSize * 0.001  # measured in milimeters

        ###### BEGIN PROCESSING IMAGE####################################################
        # import image and convert it into an array
        self.imArray = load_image(pathname)

        # data_reduction to generate 1D spectra, Q
        Qlist, IntAve = self.data_reduction(d, Rot, tilt, lamda, x0, y0,
                                            pixelSize)

        ###### SAVE PLOTS ###############################################################
        # save 1D spectra as a *.csv
        save_1Dcsv(Qlist, IntAve, fileRoot, save_path)

        ###### EXTRACT ATTRIBUTES #######################################################
        # extract composition information if the information is available
        # extract the number of peaks in 1D spectra as attribute3 by default
        newRow3, peaks = ext_peak_num(Qlist, IntAve, index)
        attDict['numPeaks'] = len(peaks)
        #attribute3.append(newRow3)
        #attributes = np.array(attribute3)

        # save 1D plot with detected peaks shown in the plot
        if self.QRange:
            titleAddStr = ', Q:' + str(self.QRange) + ', Chi:' + str(
                self.ChiRange)
        else:
            titleAddStr = '.'
        save_1Dplot(Qlist,
                    IntAve,
                    peaks,
                    fileRoot,
                    save_path,
                    titleAdd=titleAddStr)

        if True:
            # extract maximum/average intensity from 1D spectra as attribute1
            newRow1 = ext_max_ave_intens(IntAve, index)
            attDict['scanNo'], attDict['Imax'], attDict['Iave'], attDict[
                'I_ratio'] = newRow1
            #attribute1.append(newRow1)
            #attributes = np.concatenate((attribute1, attributes), axis=1)

        #if True:
        ## save 1D texture spectra as a plot (*.png) and *.csv
        #Qlist_texture, texture = save_texture_plot_csv(Q, chi, cake, fileRoot, save_path)
        ## extract texture square sum from the 1D texture spectra as attribute2
        #newRow2 = ext_text_extent(Qlist_texture, texture, index)
        #attDict['textureSum'] = newRow2[1]
        ##attribute2.append(newRow2)
        ##attributes = np.concatenate((attribute2, attributes), axis=1)

        if False:
            # extract neighbor distances as attribute4
            newRow4 = nearst_neighbor_distance(index, Qlist, IntAve,
                                               folder_path, save_path,
                                               base_filename,
                                               num_of_smpls_per_row)
            #attribute4.append(newRow4)
            #attributes = np.concatenate((attribute4, attributes), axis=1)

        if True:
            # extract signal-to-noise ratio
            try:
                newRow5 = ext_SNR(index, IntAve)
            except:
                traceback.print_exc()
                self.emit(
                    SIGNAL("addToConsole(PyQt_PyObject)"),
                    "----------------ERROR: Optimal parameters not found.----------------"
                )
                self.abort_flag = True
                return
            attDict['SNR'] = newRow5[1]
            #attribute5.append(newRow5)
            #attributes = np.concatenate((attribute5, attributes), axis=1)

        # add features (floats) to master metadata
        attDict['scanNo'] = int(index)
        addFeatsToMaster(attDict, masterPath)

        # -*- coding: utf-8 -*-
        """
Example #14
0
def initialize():
   for index in range(0, len(item_files)):
       items.append(load_image(item_files[index], True))
Example #15
0
    def beginReduction(
        self, pathname
    ):  # Defines which lines are wanted/unwanted when writing previous run information during transforming
        '''
        Processing script, reducing images to 1D plots (Q-Chi, Texture, etc)
        '''
        # print('\n')
        # print('******************************************** Begin image reduction...')
        # PP: beam polarization, according to beamline setup.
        # Contact beamline scientist for this number
        self.PP = 0.95
        pixelSize = 79  # detector pixel size, measured in microns

        # pathname was imageFullName
        folder_path = os.path.dirname(pathname)
        filename = os.path.basename(pathname)
        # fileRoot was imageFilename
        fileRoot, ext = os.path.splitext(filename)
        index = re.match('.*?([0-9]+).[a-zA-Z]+$', filename).group(1)
        base_filename = re.match('(.*?)[0-9]+.[a-zA-Z]+$',
                                 filename).group(1)  # name w/o ind

        # Master CSV path
        masterPath = os.path.join(
            folder_path, base_filename + 'master.csv'
        )  # Defines which lines are wanted/unwanted when writing previous run information during transforming

        # generate a folder to put processed files
        save_path = self.processedPath

        # make master index (vestigial)
        master_index = str(int(random.random() * 100000000))

        attDict = dict.fromkeys([
            'scanNo', 'SNR', 'textureSum', 'Imax', 'Iave', 'I_ratio',
            'numPeaks'
        ])
        #attribute1=[['scan#', 'Imax', 'Iave', 'Imax/Iave']]
        #attribute2=[['scan#', 'texture_sum']]
        #attribute3=[['scan#', 'peak_num']]
        #attribute4=[['scan#', 'neighbor_distance']]
        #attribute5=[['scan#', 'SNR']]

        ###### BEGIN READING CALIB FILE ################################################## Defines which lines are wanted/unwanted when writing previous run information during transforming

        # initializing params, transform the calibration parameters from WxDiff to Fit2D
        d_in_pixel = float(str(self.detectorData[0]))
        Rotation_angle = float(str(self.detectorData[1]))
        tilt_angle = float(str(self.detectorData[2]))
        lamda = float(str(self.detectorData[3]))
        x0 = float(str(self.detectorData[4]))
        y0 = float(str(self.detectorData[5]))
        #d_in_pixel, Rotation_angle, tilt_angle, lamda, x0, y0 = parse_calib(calibPath)
        Rot = (np.pi * 2 - Rotation_angle) / (2 *
                                              np.pi) * 360  # detector rotation
        tilt = tilt_angle / (2 * np.pi) * 360  # detector tilt  # wavelength
        d = d_in_pixel * pixelSize * 0.001  # measured in milimeters

        ###### BEGIN PROCESSING IMAGE####################################################
        # import image and convert it into an array
        self.imArray = load_image(pathname.rstrip(), self.curDetector)
        if self.imArray is None:
            self.emit(
                SIGNAL("addToConsole(PyQt_PyObject)"),
                "Could not transform image, maybe it's because you're using the wrong detector."
            )
            return
        self.imArray = np.flipud(self.imArray)

        # data_reduction to generate Q-chi, Q
        try:
            Q, chi, cake, = self.data_reduction(d, Rot, tilt, lamda, x0, y0,
                                                pixelSize)
        except:  # non-optimal parameters
            traceback.print_exc()
            self.emit(SIGNAL("addToConsole(PyQt_PyObjct)"),
                      "Could not perform data reduction!")
            # print("NOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO")
            return

        ###### SAVE PLOTS ###############################################################
        # save Qchi as a plot *.png and *.mat
        qname = save_Qchi(Q, chi, cake, fileRoot, save_path)
        return 1
Example #16
0
def main():
#Initialize objects
    clock = pygame.time.Clock()
    quit = False
    font = pygame.font.Font(None, 24)
    car = player.Player()
    cam = camera.Camera()
    timer.initialize()
    aim = timer.Finish()
    linear = LinearSearch.LinearSearch()

    #load different numbers of a class and save them as listvariables for
    # iteration over within the while loop
    engine = [timer.Engine() for i in range (0,2)]
    wheel = [timer.Wheels() for i in range (0,8)]
    steeringwheel = [timer.SteeringWheel() for i in range (0,3)]
    gearbox = [timer.Gearbox() for i in range (0,3)]
    breakpedal = [timer.BreakPedal() for i in range (0,5)]

    finish1 = finish.Alert()

    #Set sprite groups for different items
    map1 = pygame.sprite.Group()
    player1 = pygame.sprite.Group()
    engines = pygame.sprite.Group()
    wheels = pygame.sprite.Group()
    steeringwheels = pygame.sprite.Group()
    gearboxes = pygame.sprite.Group()
    breakpedals = pygame.sprite.Group()

    timeout = pygame.sprite.Group()

    #generate tiles
    for tile_num in range (0, len(map.map_tiles)):
        map.map_files.append(load_image(map.map_tiles[tile_num], False))
    for x in range (0, 24):
        for y in range (0, 24):
            map1.add(map.Map(map.map_1[x][y], x * 400, y * 400))


    #Add items to the map with the same number of items as classes created previously
    for i in range (0,2):
        engines.add(engine[i])
        enginelocationX.append(engine[i].returnEngineX())
        enginelocationY.append(engine[i].returnEngineY())

    for i in range (0,8):
        wheels.add(wheel[i])

    for i in range (0,3):
        steeringwheels.add(steeringwheel[i])

    for i in range (0,3):
        gearboxes.add(gearbox[i])

    for i in range (0,5):
        breakpedals.add(breakpedal[i])

    timeout.add(finish1)

    player1.add(car)

    cam.set_pos(car.x, car.y)

    aim.ReverseInsertionSort()

    while not quit:

        closestengine = dijkstras.addnodes(enginelocationX,enginelocationY,int(car.x + 700),int(car.y + 600))
        dijkstras.clearnodes()


    #Check for menu/reset, (keyup event - trigger ONCE)
        for event in pygame.event.get():
            if event.type == pygame.KEYUP:
                if (keys[K_q]):
                    pygame.quit()
                    sys.exit(0)

            if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                quit = True
                break

    #Check for key input. (KEYDOWN, trigger often)
        keys = pygame.key.get_pressed()
        #if (target.timeleft > 0):
        if keys[K_LEFT]:
            car.steerleft()
        if keys[K_RIGHT]:
            car.steerright()
        if keys[K_UP]:
            car.accelerate()
        else:
            car.soften()
        if keys[K_DOWN]:
            car.deaccelerate()

        cam.set_pos(car.x, car.y)



        #Show text data.
        text_fps = font.render('FPS: ' + str(int(clock.get_fps())), 1, (224, 16, 16))
        textpos_fps = text_fps.get_rect(centery=25, centerx=60)

        text_score = font.render('Score: ' + str(aim.score), 1, (224, 16, 16))
        textpos_score = text_fps.get_rect(centery=45, centerx=60)

        text_timer = font.render('Timer: ' + str(int((aim.timeleft / 60)/60)) + ":" + str(int((aim.timeleft / 60) % 60)), 1, (224, 16, 16))
        textpos_timer = text_fps.get_rect(centery=65, centerx=60)

        text_first = font.render(str(aim.first), 1, (255,255,255))
        textpos_first = text_fps.get_rect(centery=150, centerx=60)

        text_second = font.render(str(aim.second), 1, (255,255,255))
        textpos_second = text_fps.get_rect(centery=170, centerx=60)

        text_third = font.render(str(aim.third), 1, (255,255,255))
        textpos_third = text_fps.get_rect(centery=190, centerx=60)

        text_fourth = font.render(str(aim.fourth), 1, (255,255,255))
        textpos_fourth = text_fps.get_rect(centery=210, centerx=60)

        text_fith = font.render(str(aim.fith), 1, (255,255,255))
        textpos_fith = text_fps.get_rect(centery=230, centerx=60)

        text_closestengine = font.render("The Closest Engine is: " +linear.linearSearch(list(closestengine[1]), "point1") + " which is " + str(closestengine[0]) + " units from you", 1, (255,255,255))
        textpos_closestengine = text_fps.get_rect(centery = 350, centerx=60)

        linear.reset()

        #Render Scene.
        window.blit(background, (0,0))

        map1.update(cam.x, cam.y)
        map1.draw(window)

        car.grass(window.get_at(((CENTER_W + 25, CENTER_H + 50))).g)

        aim.ReverseInsertionSort()

        player1.update(cam.x, cam.y)
        player1.draw(window)


#Check for collision between the car and all the items placed on the map
#if collision has occured then replace the item in a new location and run reverse insetion sort
        for i in range (0,2):
            engine[i].update(cam.x, cam.y)
            if pygame.sprite.spritecollide(car, engines, True):
                engine[i].claim_item()
                engine[i].generate_finish()
                enginelocationX[i] = engine[i].returnEngineX()
                enginelocationY[i] = engine[i].returnEngineY()
                engine[i].add(engines)
                aim.ReverseInsertionSort()


        for i in range (0,8):
            wheel[i].update(cam.x, cam.y)
            if pygame.sprite.spritecollide(car, wheels, True):
                wheel[i].claim_item()
                wheel[i].generate_finish()
                wheel[i].add(wheels)
                aim.ReverseInsertionSort()

        for i in range (0,3):
            gearbox[i].update(cam.x, cam.y)
            if pygame.sprite.spritecollide(car, gearboxes, True):
                gearbox[i].claim_item()
                gearbox[i].generate_finish()
                gearbox[i].add(gearboxes)
                aim.ReverseInsertionSort()

        for i in range (0,3):
            steeringwheel[i].update(cam.x, cam.y)
            if pygame.sprite.spritecollide(car, steeringwheels, True):
                steeringwheel[i].claim_item()
                steeringwheel[i].generate_finish()
                steeringwheel[i].add(steeringwheels)
                aim.ReverseInsertionSort()

        for i in range (0,5):
            breakpedal[i].update(cam.x, cam.y)
            if pygame.sprite.spritecollide(car, breakpedals, True):
                breakpedal[i].claim_item()
                breakpedal[i].generate_finish()
                breakpedal[i].add(breakpedals)
                aim.ReverseInsertionSort()


#Draw all sprite groups onto window
        engines.draw(window)
        wheels.draw(window)
        gearboxes.draw(window)
        steeringwheels.draw(window)
        breakpedals.draw(window)


#If timer runs down to 0, reposition all text and run bubblesort on the information to reorder and reorganise
        if (aim.timeleft == 0):
            timeout.draw(window)
            car.speed = 0
            font = pygame.font.Font(None, 42)
            text_score = font.render('Final Score: ' + str(aim.score), 1, (224, 16, 16))
            textpos_score = text_fps.get_rect(centery=CENTER_H/2+200, centerx=CENTER_W-60)
            textpos_first = text_fps.get_rect(centery=CENTER_H/2+250, centerx=CENTER_W-40)
            textpos_second = text_fps.get_rect(centery=CENTER_H/2+280, centerx=CENTER_W-40)
            textpos_third = text_fps.get_rect(centery=CENTER_H/2+310, centerx=CENTER_W-40)
            textpos_fourth = text_fps.get_rect(centery=CENTER_H/2+340, centerx=CENTER_W-40)
            textpos_fith = text_fps.get_rect(centery=CENTER_H/2+370, centerx=CENTER_W-40)
            aim.bubblesort()


#Render the text onto the screen using predefined variables for content and position
        font = pygame.font.Font(None, 24)
        window.blit(text_fps, textpos_fps)
        window.blit(text_score, textpos_score)
        window.blit(text_timer, textpos_timer)
        window.blit(text_first, textpos_first)
        window.blit(text_second, textpos_second)
        window.blit(text_third, textpos_third)
        window.blit(text_fourth, textpos_fourth)
        window.blit(text_fith, textpos_fith)
        window.blit(text_closestengine, textpos_closestengine)
        pygame.display.flip()

        aim.update()

        clock.tick(64)
def SAXSDimReduce(calibPath, pathname, config):  #QRange=None, ChiRange=None):
    '''
    Processing script, reducing images to 1D plots (Q-Chi, Texture, etc)
    '''
    print('\n')
    print(
        '******************************************** Begin image reduction...'
    )
    # PP: beam polarization, according to beamline setup.
    # Contact beamline scientist for this number
    PP = 0.95
    pixelSize = 79  # detector pixel size, measured in microns

    # pathname was imageFullName
    folder_path = os.path.dirname(pathname)
    filename = os.path.basename(pathname)
    # fileRoot was imageFilename
    fileRoot, ext = os.path.splitext(filename)
    index = re.match('.*?([0-9]+).[a-zA-Z]+$', filename).group(1)
    base_filename = re.match('(.*?)[0-9]+.[a-zA-Z]+$',
                             filename).group(1)  # name w/o ind

    # Master CSV path
    masterPath = os.path.join(folder_path, base_filename + 'master.csv')

    # generate a folder to put processed files
    save_path = os.path.join(folder_path, 'Processed')
    if not os.path.exists(save_path):
        os.makedirs(save_path)
    # make master index (vestigial)
    master_index = str(int(random.random() * 100000000))

    attDict = dict.fromkeys(
        ['scanNo', 'SNR', 'textureSum', 'Imax', 'Iave', 'I_ratio', 'numPeaks'])
    #attribute1=[['scan#', 'Imax', 'Iave', 'Imax/Iave']]
    #attribute2=[['scan#', 'texture_sum']]
    #attribute3=[['scan#', 'peak_num']]
    #attribute4=[['scan#', 'neighbor_distance']]
    #attribute5=[['scan#', 'SNR']]

    ###### BEGIN READING CALIB FILE #################################################
    # initializing params, transform the calibration parameters from WxDiff to Fit2D
    d_in_pixel, Rotation_angle, tilt_angle, lamda, x0, y0 = parse_calib(
        calibPath)
    Rot = (np.pi * 2 - Rotation_angle) / (2 * np.pi) * 360  # detector rotation
    tilt = tilt_angle / (2 * np.pi) * 360  # detector tilt  # wavelength
    d = d_in_pixel * pixelSize * 0.001  # measured in milimeters

    print 'Processing image file: ' + pathname
    if not config:
        print('no config file found')
    else:
        QRange = (config['Qmin'], config['Qmax'])
        ChiRange = (config['ChiMin'], config['ChiMax'])
        # require all bounds to exist, currently can't check default limits
        if (any(isinstance(n, str) for n in QRange)
                or any(isinstance(m, str) for m in ChiRange)):
            print('Pass found, ignoring Q,Chi limits')
            QRange, ChiRange = None, None

        print('config read')

    ###### BEGIN PROCESSING IMAGE####################################################
    # import image and convert it into an array
    imArray = load_image(pathname)

    # data_reduction to generate Q-chi and 1D spectra, Q
    Q, chi, cake, Qlist, IntAve = data_reduction(imArray,
                                                 d,
                                                 Rot,
                                                 tilt,
                                                 lamda,
                                                 x0,
                                                 y0,
                                                 PP,
                                                 pixelSize,
                                                 QRange=QRange,
                                                 ChiRange=ChiRange)

    ###### SAVE PLOTS ###############################################################
    # save Qchi as a plot *.png and *.mat
    save_Qchi(Q, chi, cake, fileRoot, save_path)
    # save 1D spectra as a *.csv
    save_1Dcsv(Qlist, IntAve, fileRoot, save_path)

    ###### EXTRACT ATTRIBUTES #######################################################
    # extract composition information if the information is available
    # extract the number of peaks in 1D spectra as attribute3 by default
    newRow3, peaks = ext_peak_num(Qlist, IntAve, index)
    attDict['numPeaks'] = len(peaks)
    #attribute3.append(newRow3)
    #attributes = np.array(attribute3)

    # save 1D plot with detected peaks shown in the plot
    if QRange:
        titleAddStr = ', Q:' + str(QRange) + ', Chi:' + str(ChiRange)
    else:
        titleAddStr = '.'
    save_1Dplot(Qlist,
                IntAve,
                peaks,
                fileRoot,
                save_path,
                titleAdd=titleAddStr)

    if True:
        # extract maximum/average intensity from 1D spectra as attribute1
        newRow1 = ext_max_ave_intens(IntAve, index)
        attDict['scanNo'], attDict['Imax'], attDict['Iave'], attDict[
            'I_ratio'] = newRow1
        #attribute1.append(newRow1)
        #attributes = np.concatenate((attribute1, attributes), axis=1)

    if True:
        # save 1D texture spectra as a plot (*.png) and *.csv
        Qlist_texture, texture = save_texture_plot_csv(Q, chi, cake, fileRoot,
                                                       save_path)
        # extract texture square sum from the 1D texture spectra as attribute2
        newRow2 = ext_text_extent(Qlist_texture, texture, index)
        attDict['textureSum'] = newRow2[1]
        #attribute2.append(newRow2)
        #attributes = np.concatenate((attribute2, attributes), axis=1)

    if False:
        # extract neighbor distances as attribute4
        newRow4 = nearst_neighbor_distance(index, Qlist, IntAve, folder_path,
                                           save_path, base_filename,
                                           num_of_smpls_per_row)
        #attribute4.append(newRow4)
        #attributes = np.concatenate((attribute4, attributes), axis=1)

    if True:
        # extract signal-to-noise ratio
        newRow5 = ext_SNR(index, IntAve)
        attDict['SNR'] = newRow5[1]
        #attribute5.append(newRow5)
        #attributes = np.concatenate((attribute5, attributes), axis=1)

    # add features (floats) to master metadata
    attDict['scanNo'] = int(index)
    addFeatsToMaster(attDict, masterPath)
Example #18
0
import sys
from random import choice
import numpy as np
import matplotlib.pyplot as plt
from image_loader import load_image
from navigation import movement, skeleton

# Load the image
print "Loading image..."
data = load_image(sys.argv[1])

print "Generating skeleton..."
skel = skeleton.make_skeleton(data, mindist=10)

# Draw!
plt.figure()
plt.imshow(data, cmap=plt.cm.gray, interpolation='nearest')

# Compute the paths
print "Finding paths..."
start = (1, 132)

paths = movement.find_all_paths(start, skel)
closest_path = movement.find_closest_path(start, paths)

print "Plotting!"
for path in paths:
    color = np.random.rand(3)

    plt.plot(*path.end, color=color, marker='o')
    plt.plot(*path.points, color=color, marker=',')
    axes[0].imshow(z)
    axes[0].plot([x0, x1], [y0, y1], 'k-')
    axes[0].plot(x0, y0, 'go')
    axes[0].plot(x1, y1, 'ro')
    axes[0].axis('image')
    axes[0].set_title('Binary edges image')
    
    axes[1].plot(profile,'ko-')
    axes[1].plot(0,profile[0],'go')
    axes[1].plot(len(profile)-1,profile[-1],'ro')
    axes[1].set_title('Profile across edges array')
    axes[1].set_xlabel('Pixel distance')


# Run functions in order ======================================================

# Example edge binary image
test_file = pth.join('.', 'tests', 'test_data', '10_circles_colour.gif')
image_in = load_image(test_file)
z = detect_edge(image_in)

# Select coords
coords = binaryarray2coords(z)

# Calculate profile from coords
profile = coords2profile(coords)

# Plot result
plot_edges_profile(z,coords,profile)

Example #20
0
def main():
    #Initialize objects
    clock = pygame.time.Clock()
    quit = False
    font = pygame.font.Font(None, 24)
    car = player.Player()
    cam = camera.Camera()
    timer.initialize()
    aim = timer.Finish()
    linear = LinearSearch.LinearSearch()

    #load different numbers of a class and save them as listvariables for
    # iteration over within the while loop
    engine = [timer.Engine() for i in range(0, 2)]
    wheel = [timer.Wheels() for i in range(0, 8)]
    steeringwheel = [timer.SteeringWheel() for i in range(0, 3)]
    gearbox = [timer.Gearbox() for i in range(0, 3)]
    breakpedal = [timer.BreakPedal() for i in range(0, 5)]

    finish1 = finish.Alert()

    #Set sprite groups for different items
    map1 = pygame.sprite.Group()
    player1 = pygame.sprite.Group()
    engines = pygame.sprite.Group()
    wheels = pygame.sprite.Group()
    steeringwheels = pygame.sprite.Group()
    gearboxes = pygame.sprite.Group()
    breakpedals = pygame.sprite.Group()

    timeout = pygame.sprite.Group()

    #generate tiles
    for tile_num in range(0, len(map.map_tiles)):
        map.map_files.append(load_image(map.map_tiles[tile_num], False))
    for x in range(0, 24):
        for y in range(0, 24):
            map1.add(map.Map(map.map_1[x][y], x * 400, y * 400))

    #Add items to the map with the same number of items as classes created previously
    for i in range(0, 2):
        engines.add(engine[i])
        enginelocationX.append(engine[i].returnEngineX())
        enginelocationY.append(engine[i].returnEngineY())

    for i in range(0, 8):
        wheels.add(wheel[i])

    for i in range(0, 3):
        steeringwheels.add(steeringwheel[i])

    for i in range(0, 3):
        gearboxes.add(gearbox[i])

    for i in range(0, 5):
        breakpedals.add(breakpedal[i])

    timeout.add(finish1)

    player1.add(car)

    cam.set_pos(car.x, car.y)

    aim.ReverseInsertionSort()

    while not quit:

        closestengine = dijkstras.addnodes(enginelocationX, enginelocationY,
                                           int(car.x + 700), int(car.y + 600))
        dijkstras.clearnodes()

        #Check for menu/reset, (keyup event - trigger ONCE)
        for event in pygame.event.get():
            if event.type == pygame.KEYUP:
                if (keys[K_q]):
                    pygame.quit()
                    sys.exit(0)

            if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                quit = True
                break

    #Check for key input. (KEYDOWN, trigger often)
        keys = pygame.key.get_pressed()
        #if (target.timeleft > 0):
        if keys[K_LEFT]:
            car.steerleft()
        if keys[K_RIGHT]:
            car.steerright()
        if keys[K_UP]:
            car.accelerate()
        else:
            car.soften()
        if keys[K_DOWN]:
            car.deaccelerate()

        cam.set_pos(car.x, car.y)

        #Show text data.
        text_fps = font.render('FPS: ' + str(int(clock.get_fps())), 1,
                               (224, 16, 16))
        textpos_fps = text_fps.get_rect(centery=25, centerx=60)

        text_score = font.render('Score: ' + str(aim.score), 1, (224, 16, 16))
        textpos_score = text_fps.get_rect(centery=45, centerx=60)

        text_timer = font.render(
            'Timer: ' + str(int((aim.timeleft / 60) / 60)) + ":" +
            str(int((aim.timeleft / 60) % 60)), 1, (224, 16, 16))
        textpos_timer = text_fps.get_rect(centery=65, centerx=60)

        text_first = font.render(str(aim.first), 1, (255, 255, 255))
        textpos_first = text_fps.get_rect(centery=150, centerx=60)

        text_second = font.render(str(aim.second), 1, (255, 255, 255))
        textpos_second = text_fps.get_rect(centery=170, centerx=60)

        text_third = font.render(str(aim.third), 1, (255, 255, 255))
        textpos_third = text_fps.get_rect(centery=190, centerx=60)

        text_fourth = font.render(str(aim.fourth), 1, (255, 255, 255))
        textpos_fourth = text_fps.get_rect(centery=210, centerx=60)

        text_fith = font.render(str(aim.fith), 1, (255, 255, 255))
        textpos_fith = text_fps.get_rect(centery=230, centerx=60)

        text_closestengine = font.render(
            "The Closest Engine is: " +
            linear.linearSearch(list(closestengine[1]), "point1") +
            " which is " + str(closestengine[0]) + " units from you", 1,
            (255, 255, 255))
        textpos_closestengine = text_fps.get_rect(centery=350, centerx=60)

        linear.reset()

        #Render Scene.
        window.blit(background, (0, 0))

        map1.update(cam.x, cam.y)
        map1.draw(window)

        car.grass(window.get_at(((CENTER_W + 25, CENTER_H + 50))).g)

        aim.ReverseInsertionSort()

        player1.update(cam.x, cam.y)
        player1.draw(window)

        #Check for collision between the car and all the items placed on the map
        #if collision has occured then replace the item in a new location and run reverse insetion sort
        for i in range(0, 2):
            engine[i].update(cam.x, cam.y)
            if pygame.sprite.spritecollide(car, engines, True):
                engine[i].claim_item()
                engine[i].generate_finish()
                enginelocationX[i] = engine[i].returnEngineX()
                enginelocationY[i] = engine[i].returnEngineY()
                engine[i].add(engines)
                aim.ReverseInsertionSort()

        for i in range(0, 8):
            wheel[i].update(cam.x, cam.y)
            if pygame.sprite.spritecollide(car, wheels, True):
                wheel[i].claim_item()
                wheel[i].generate_finish()
                wheel[i].add(wheels)
                aim.ReverseInsertionSort()

        for i in range(0, 3):
            gearbox[i].update(cam.x, cam.y)
            if pygame.sprite.spritecollide(car, gearboxes, True):
                gearbox[i].claim_item()
                gearbox[i].generate_finish()
                gearbox[i].add(gearboxes)
                aim.ReverseInsertionSort()

        for i in range(0, 3):
            steeringwheel[i].update(cam.x, cam.y)
            if pygame.sprite.spritecollide(car, steeringwheels, True):
                steeringwheel[i].claim_item()
                steeringwheel[i].generate_finish()
                steeringwheel[i].add(steeringwheels)
                aim.ReverseInsertionSort()

        for i in range(0, 5):
            breakpedal[i].update(cam.x, cam.y)
            if pygame.sprite.spritecollide(car, breakpedals, True):
                breakpedal[i].claim_item()
                breakpedal[i].generate_finish()
                breakpedal[i].add(breakpedals)
                aim.ReverseInsertionSort()

#Draw all sprite groups onto window
        engines.draw(window)
        wheels.draw(window)
        gearboxes.draw(window)
        steeringwheels.draw(window)
        breakpedals.draw(window)

        #If timer runs down to 0, reposition all text and run bubblesort on the information to reorder and reorganise
        if (aim.timeleft == 0):
            timeout.draw(window)
            car.speed = 0
            font = pygame.font.Font(None, 42)
            text_score = font.render('Final Score: ' + str(aim.score), 1,
                                     (224, 16, 16))
            textpos_score = text_fps.get_rect(centery=CENTER_H / 2 + 200,
                                              centerx=CENTER_W - 60)
            textpos_first = text_fps.get_rect(centery=CENTER_H / 2 + 250,
                                              centerx=CENTER_W - 40)
            textpos_second = text_fps.get_rect(centery=CENTER_H / 2 + 280,
                                               centerx=CENTER_W - 40)
            textpos_third = text_fps.get_rect(centery=CENTER_H / 2 + 310,
                                              centerx=CENTER_W - 40)
            textpos_fourth = text_fps.get_rect(centery=CENTER_H / 2 + 340,
                                               centerx=CENTER_W - 40)
            textpos_fith = text_fps.get_rect(centery=CENTER_H / 2 + 370,
                                             centerx=CENTER_W - 40)
            aim.bubblesort()

#Render the text onto the screen using predefined variables for content and position
        font = pygame.font.Font(None, 24)
        window.blit(text_fps, textpos_fps)
        window.blit(text_score, textpos_score)
        window.blit(text_timer, textpos_timer)
        window.blit(text_first, textpos_first)
        window.blit(text_second, textpos_second)
        window.blit(text_third, textpos_third)
        window.blit(text_fourth, textpos_fourth)
        window.blit(text_fith, textpos_fith)
        window.blit(text_closestengine, textpos_closestengine)
        pygame.display.flip()

        aim.update()

        clock.tick(64)