Exemple #1
0
def reorient_4d_image(image):
    """
    Reorients the data to radiological, one TR at a time
    """
    for i in np.arange(image.shape[3]):

        if i == 0:
            newimage = np.transpose(image[:, :, :, i], (2,0,1))
            newimage = np.rot90(newimage, 2)

        elif i == 1:
            tmpimage = np.transpose(image[:, :, :, i], (2,0,1))
            tmpimage = np.rot90(tmpimage, 2)
            newimage = np.concatenate((newimage[...,np.newaxis],
                                       tmpimage[...,np.newaxis]), axis=3)

        else:
            tmpimage = np.transpose(image[:, :, :, i], (2,0,1))
            tmpimage = np.rot90(tmpimage, 2)
            newimage = np.concatenate((newimage,
                                       tmpimage[...,np.newaxis]), axis=3)

    image = copy(newimage)

    return image
 def flip_rotate_color_image(self,image,angles_90, flip_on):
     for current_color in range(0,image[0,0,:].size):
         if flip_on:
             image[:,:,current_color]=np.rot90(np.flipud(image[:,:,current_color]),angles_90)            
         else:
             image[:,:,current_color]=np.rot90(image[:,:,current_color],angles_90)
     return image
Exemple #3
0
    def get_output(self, idx):
        img_id=idx/self.pertnum
        pert_id=idx%self.pertnum
        rot_id=pert_id%self.param['rotate']
        off_id=pert_id/self.param['rotate']
        [h, w]=self.output[img_id].shape
        [dy, dx]=self.get_offset(h, w, off_id)
        dy+=self.param['mrgsize']
        dx+=self.param['mrgsize']
        res=self.output[img_id][dy:dy+self.param['outsize'], dx:dx+self.param['outsize']]
        #res=np.rot90(res) #rotate 90
        if rot_id==1:
            res=np.fliplr(res)
        elif rot_id==2:
            res=np.flipud(res).T
        elif rot_id==3:
            res=res.T
        elif rot_id==4:
            res=np.fliplr(res).T
        elif rot_id==5:
            res=np.flipud(res)
        elif rot_id==6:
            res=np.rot90(res,2)
        elif rot_id==7:
            res=np.rot90(res,2).T

        return res
Exemple #4
0
def generate_image(data, is_partial=False, content_range=None):
    fig = plt.figure()
    if data.ndim == 1:
        plt.plot(data)
    elif data.ndim == 2:
        data = np.asarray(data).real
        mat = plt.matshow(np.rot90(data), cmap=plt.cm.viridis)
        mat.axes.get_xaxis().set_visible(False)
        mat.axes.get_yaxis().set_visible(False)
    elif data.ndim == 3 and data.shape[-1] in (3, 4):
        data = np.array(data)
        mat = plt.imshow(np.rot90(data))
        mat.axes.get_xaxis().set_visible(False)
        mat.axes.get_yaxis().set_visible(False)
    else:
        raise ValueError('cannot handle dimensions > 3')
    bio = BytesIO()
    plt.savefig(bio, bbox_inches='tight', pad_inches=0, format='png')
    bio.seek(0)
    fig.clf()
    plt.close('all')
    return TempResult(
            bio.read(),
            'image/png',
            is_partial=is_partial,
            content_range=content_range)
def rotate_data(bg, overlay, slices_list, axis_name, shape):
    # Rotate the data as required
    # Return the rotated data, and an updated slice list if necessary
    if axis_name == 'axial':
        # Align so that right is right
        overlay = np.rot90(overlay)
        overlay = np.fliplr(overlay)
        bg = np.rot90(bg)
        bg = np.fliplr(bg)
    
    elif axis_name == 'coronal':
        overlay = np.rot90(overlay)
        bg = np.rot90(bg)
        overlay = np.flipud(np.swapaxes(overlay, 0, 2))
        bg = np.flipud(np.swapaxes(bg, 0, 2))
        slices_list[1] = [ shape - n - 3 for n in slices_list[1] ] 
        
    elif axis_name == 'sagittal':
        overlay = np.flipud(np.swapaxes(overlay, 0, 2))
        bg = np.flipud(np.swapaxes(bg, 0, 2))
    
    else:
        print '\n************************'
        print 'ERROR: data could not be rotated\n'
        parser.print_help()
        sys.exit()
    
    return bg, overlay, slices_list
    def plot_images(self, fig, data, number_images, subplot_index, label):
        """Method to plot the images on the PDF for the first page.

        :param fig: figure from matplotlib
        :param data: numpy array of the images (3D) to display
        :param number_images: number of images for the subplot (6)
        :param subplot_index: index of the line to display (1-6)
        :param label: y-label
        :return: None
        """
        ax = fig.add_subplot(number_images, 3, 3*subplot_index+1)
        ax.imshow(np.rot90(data[:, :, data.shape[2]/2]), cmap='gray')
        if subplot_index == 0:
            ax.set_title('Axial', fontsize=7)
        ax.set_ylabel(label, fontsize=9)
        ax.set_xticks([])
        ax.set_yticks([])
        ax = fig.add_subplot(number_images, 3, 3*subplot_index+2)
        ax.imshow(np.rot90(data[:, data.shape[1]/2, :]), cmap='gray')
        if subplot_index == 0:
            ax.set_title('Coronal', fontsize=7)
        ax.set_axis_off()
        ax = fig.add_subplot(number_images, 3, 3*subplot_index+3)
        ax.imshow(np.rot90(data[data.shape[0]/2, :, :]), cmap='gray')
        if subplot_index == 0:
            ax.set_title('Sagittal', fontsize=7)
        ax.set_axis_off()
    def displayFrame(self, update_locs):
        if self.movie_file:

            # Get the current frame.
            frame = self.movie_file.loadAFrame(self.cur_frame).astype(numpy.float)
            if self.ui.oriCheckBox.isChecked():
                frame = numpy.rot90(numpy.rot90(frame))
            else:
                frame = numpy.transpose(frame)


            # Create the 3D-DAOSTORM molecule items.
            nm_per_pixel = self.ui.nmPerPixelSpinBox.value()
            multi_mols = []
            if update_locs and self.multi_list:
                multi_mols = self.multi_list.createMolItems(self.cur_frame+1, nm_per_pixel)

            # Create the Insight3 molecule items.
            i3_mols = []
            if update_locs and self.i3_list:
                i3_mols = self.i3_list.createMolItems(self.cur_frame+1, nm_per_pixel)

            self.movie_view.newFrame(frame,
                                     multi_mols,
                                     i3_mols,
                                     self.ui.minSpinBox.value(),
                                     self.ui.maxSpinBox.value())
def main():
    from sys import argv
    if len(argv) < 4:
        print "Insufficient arguments!"
        print "Proper Usage: %s [db_path] [experiment_path] [offset_file]"
        return

    db_path = path.expanduser(argv[1])
    db_man = io.ImageDbManager(db_path, readonly=False)

    experiment_path = path.expanduser(argv[2])
    meta_man = io.MetadataManager(experiment_path)

    offset_path = path.expanduser(argv[3])
    offsets = json.load(open(offset_path))

    for i, offset in enumerate(offsets):
        print "Updating image %d/%d" % (i, len(offsets))
        key = offset['vsi_path'][2:]

        try:
            image = db_man.get_image(key)
            image.region_map_offset = offset['pad_size']

            metadata = meta_man.get_entry_by_attribute('vsiPath', key)
            region_map = io.load_mhd(path.join(experiment_path, metadata['registeredAtlasLabelsPath']))[0]
            hemisphere_map = io.load_mhd(path.join(experiment_path, metadata['registeredHemisphereLabelsPath']))[0]

            image.region_map = numpy.rot90(region_map, k=2)
            image.hemisphere_map = numpy.rot90(hemisphere_map, k=2)

            db_man.add_image(image)

        except:
            print "Failed to update image with key: %s" % key
Exemple #9
0
    def do_cut(self, map, affine):
        """ Cut the 3D volume into a 2D slice

            Parameters
            ==========
            map: 3D ndarray
                The 3D volume to cut
            affine: 4x4 ndarray
                The affine of the volume
        """
        coords = [0, 0, 0]
        coords['yxz'.index(self.direction)] = self.coord
        x_map, y_map, z_map = [int(round(c)) for c in
                               coord_transform(coords[0],
                                               coords[1],
                                               coords[2],
                                               np.linalg.inv(affine))]
        if self.direction == 'x':
            cut = np.rot90(map[:, y_map, :])
        elif self.direction == 'y':
            cut = np.rot90(map[x_map, :, :])
        elif self.direction == 'z':
            cut = np.rot90(map[:, :, z_map])
        else:
            raise ValueError('Invalid value for direction %s' %
                             self.direction)
        return cut
 def modZernFitUnwrapped(self, useMask=False, radius=0):
     #geometry = self._control.slm.getGeometry()
     geometry = self._getGeo()
     d = geometry.d
     if radius==0:
         r = d/2
     else:
         r = radius
     cx = geometry.cx
     cy = geometry.cy
     if self._zernFitUnwrappedModes is not None:
         print "ZernFitUnwrapped Modes: ", self._zernFitUnwrappedModes
         print "Radius for zernCalc: ", r
         zernCalc = libtim.zern.calc_zernike(self._zernFitUnwrappedModes, r, mask=useMask)
         
         MOD = -1*zernCalc
         MOD = np.flipud(MOD)
         MOD = np.rot90(MOD)
         MOD = np.rot90(-1.0*MOD)
         #MOD = interpolation.shift(MOD,(cy-255.5,cx-255.5),order=0,
         #                                       mode='nearest')
         newMOD = np.zeros((geometry.nx,geometry.ny))
         nx,ny = MOD.shape
         newMOD[cy-np.floor(nx/2.):cy+np.ceil(nx/2.),cx-np.floor(ny/2.):cx+np.ceil(ny/2.)] = MOD.copy()
         if self.hasSLM:
             index = self._control.slm.addOther(newMOD)
         else:
             index = self._control.mirror.addOther(newMOD)
         self._modulations.append(index)
         return index
    def modulatePF_unwrapped(self):
        #geometry = self._control.slm.getGeometry()
        geometry = self._getGeo()
        MOD = -1*self.unwrap()
        MOD = np.flipud(MOD)
        MOD = np.rot90(MOD)
        cx,cy,d = geometry.cx, geometry.cy, geometry.d
        # Diameter of phase retrieval output [pxl]:
        dPhRt = (self._pupil.k_max/self._pupil.kx.max())*self._pupil.nx
        # Zoom needed to fit onto SLM map:
        zoom = d/dPhRt
        MOD = interpolation.zoom(MOD,zoom,order=0,mode='nearest')
        # Flip up down:
        #MOD = np.flipud(MOD)
        # Flip left right:
        #MOD = np.fliplr(MOD)
        #MOD = np.rot90(MOD)
        MOD = np.rot90(-1.0*MOD) #Invert and rot90
        # Shift center:
        MOD = interpolation.shift(MOD,(cy-255.5,cx-255.5),order=0,
                                                       mode='nearest')
        # Cut out center 512x512:
        c = MOD.shape[0]/2
        MOD = MOD[c-256:c+256,c-256:c+256]

        
        # Add an 'Other' modulation using the SLM API. Store the index in _modulations:
        #index = self._control.slm.addOther(MOD)
        index = self._addMOD(MOD)
        self._modulations.append(index)
        return index
Exemple #12
0
def data_reorient_udrot(d, pl, ud=None, rot90=None):
    """
    """
    print >>sys.stderr, "Reorienting...",
    if (not ud is None) and (not rot90 is None):
        if ud > 0:
            d = np.flipud(d)
        if rot90 > 0:
            d = np.rot90(d, rot90)
        print >>sys.stderr, "done."
        return d
        
    ud = pl.get_val('REORIENT_CCD_FLIPUD')
    if ud == None:
        ud = pl.get_val('CORRECTION_FLIPUD')
    ud = int(ud)
    rot90 = pl.get_val('REORIENT_CCD_ROT90')
    if rot90 == None:
        rot90 = pl.get_val('CORRECTION_ROTATION')
    rot90 = int(rot90)
    if ud > 0:
        d = np.flipud(d)
    if rot90 > 0:
        d = np.rot90(d, rot90)
    print >>sys.stderr, "done."
    return d
Exemple #13
0
def plot_spectrogram(pred_spectrogram, path, info=None, split_title=False, target_spectrogram=None, max_len=None):
	if max_len is not None:
		target_spectrogram = target_spectrogram[:max_len]
		pred_spectrogram = pred_spectrogram[:max_len]

	if info is not None:
		if split_title:
			title = split_title_line(info)
		else:
			title = info

	fig = plt.figure(figsize=(10, 8))
	# Set common labels
	fig.text(0.5, 0.18, title, horizontalalignment='center', fontsize=16)

	#target spectrogram subplot
	if target_spectrogram is not None:
		ax1 = fig.add_subplot(311)
		ax2 = fig.add_subplot(312)

		im = ax1.imshow(np.rot90(target_spectrogram), interpolation='none')
		ax1.set_title('Target Mel-Spectrogram')
		fig.colorbar(mappable=im, shrink=0.65, orientation='horizontal', ax=ax1)
		ax2.set_title('Predicted Mel-Spectrogram')
	else:
		ax2 = fig.add_subplot(211)

	im = ax2.imshow(np.rot90(pred_spectrogram), interpolation='none')
	fig.colorbar(mappable=im, shrink=0.65, orientation='horizontal', ax=ax2)

	plt.tight_layout()
	plt.savefig(path, format='png')
	plt.close()
Exemple #14
0
def doit(
    filename, raten=25, rated=1, aspectn=1, aspectd=1, rotate_180=False  # numerator  # denom  # numerator  # denom
):
    fmf = FMF.FlyMovie(filename)
    if fmf.get_format() not in ["MONO8", "RAW8"]:
        raise NotImplementedError("Only MONO8 and RAW8 formats are currently supported.")
    width = fmf.get_width() // (fmf.get_bits_per_pixel() // 8)
    height = fmf.get_height()

    Y4M_MAGIC = "YUV4MPEG2"
    Y4M_FRAME_MAGIC = "FRAME"

    inter = "Ip"  # progressive
    colorspace = "Cmono"

    out_fd = sys.stdout

    out_fd.write(
        "%(Y4M_MAGIC)s W%(width)d H%(height)d F%(raten)d:%(rated)d %(inter)s A%(aspectn)d:%(aspectd)d %(colorspace)s\n"
        % locals()
    )
    while 1:
        try:
            frame, timestamp = fmf.get_next_frame()
        except FMF.NoMoreFramesException, err:
            break

        out_fd.write("%(Y4M_FRAME_MAGIC)s\n" % locals())

        if rotate_180:
            frame = numpy.rot90(numpy.rot90(frame))

        for i in range(height):
            out_fd.write(frame[i, :].tostring())
        out_fd.flush()
def findRotationScaleTranslation(image1, image2, window=None, highpass=None):
        image1 = normalize(image1)
        image2 = normalize(image2)

        rotation, scale, rsvalue = findRotationScale(image1, image2, window, highpass)

        shape = image2.shape[0]*2, image2.shape[1]*2

        r = rotateScaleOffset(image2, -rotation, 1.0/scale, (0.0, 0.0), shape)

        o = ((shape[0] - image1.shape[0])/2, (shape[1] - image1.shape[1])/2)
        i = numpy.zeros(shape, image1.dtype)
        i[o[0]:o[0] + image1.shape[0], o[1]:o[1] + image1.shape[1]] = image1

        fft1 = numpy.fft.rfft2(i)
        fft2 = numpy.fft.rfft2(r)
        pc = phaseCorrelate(fft1, fft2, fft=True)
        peak, value = findPeak(pc)

        r180 = numpy.rot90(numpy.rot90(r))
        fft2 = numpy.fft.rfft2(r180)
        pc = phaseCorrelate(fft1, fft2, fft=True)
        peak180, value180 = findPeak(pc)

        if value < value180:
                peak = peak180
                value = value180
                rotation = (rotation + 180.0) % 360.0
                r = r180

        return rotation, scale, peak, rsvalue, value
Exemple #16
0
def _make_symmetrized_image(im_input):
    """
    add a version of itself roated by 90,180,270 degrees
    """
    im = im_input.copy()
    im += numpy.rot90(im_input, k=1)
    im += numpy.rot90(im_input, k=2)
    im += numpy.rot90(im_input, k=3)

    im *= (1.0/4.0)

    if False:
        import images
        images.multiview(im)
        images.compare_images(
            im_input,
            im,
            label1='orig',
            label2='symm',
            width=1000,
            height=1000,
        )
        if 'q'==raw_input('hit a key: '):
            stop

    return im
Exemple #17
0
    def save_3plane_vertical(self, X_cut, Y_cut, Z_cut, savefile):
        fig = pylab.figure(figsize=(4,3))
        for image in self.image_list:
            fig.add_subplot(3,1,1) ##### AXIAL
            plt.imshow(np.rot90(image[0][self.xmin:self.xmax,self.ymin:self.ymax, Z_cut],3),
                    cmap=image[1], vmax=image[2], vmin=image[3], alpha=image[4],
                    extent=[0, self.x_trans*(self.xmax - self.xmin),
                            0, self.y_trans*(self.ymax - self.ymin)],
                    origin='lower')
            plt.axis('off')

            fig.add_subplot(3,1,2) ##### COR
            plt.imshow(np.rot90(image[0][self.xmin:self.xmax, Y_cut,self.zmin:self.zmax],3),
                    cmap=image[1], vmax=image[2], vmin=image[3], alpha=image[4],
                    extent=[0, self.x_trans*(self.xmax - self.xmin),
                            0, self.z_trans*(self.zmax - self.zmin)],
                    origin='lower')
            plt.axis('off')

            fig.add_subplot(3,1,3) #### SAG
            plt.imshow(np.rot90(image[0][X_cut,self.ymin:self.ymax,self.zmin:self.zmax],3),
                    cmap=image[1], vmax=image[2], vmin=image[3], alpha=image[4],
                    extent=[0,self.y_trans*(self.ymax - self.ymin),
                            0, self.z_trans*(self.zmax - self.zmin)],
                    origin='lower')
            plt.axis('off')

        plt.savefig(savefile, dpi=500, facecolor=[0,0,0], bbox_inches=None,
                    pad_inches=0)
        plt.close()
Exemple #18
0
    def process_image(self, scanparams, pointparams, edf):
        delta, omega, alfa, beta, chi, phi, mon, transm = pointparams
        wavelength, UB = scanparams

        image = edf.GetData(0)
        header = edf.GetHeader(0)

        weights = numpy.ones_like(image)

        if not self.config.centralpixel:
            self.config.centralpixel = (int(header['y_beam']), int(header['x_beam']))
        if not self.config.sdd:
            self.config.sdd = float(header['det_sample_dist'])

        if self.config.background:
            data = image / mon
        else:
            data = image / mon / transm

        if mon == 0:
            raise errors.BackendError('Monitor is zero, this results in empty output. Scannumber = {0}, pointnumber = {1}. Did you forget to open the shutter?'.format(self.dbg_scanno, self.dbg_pointno)) 

        util.status('{4}| beta: {0:.3f}, delta: {1:.3f}, omega: {2:.3f}, alfa: {3:.3f}'.format(beta, delta, omega, alfa, time.ctime(time.time())))

        # pixels to angles
        pixelsize = numpy.array(self.config.pixelsize)
        sdd = self.config.sdd 

        app = numpy.arctan(pixelsize / sdd) * 180 / numpy.pi

        centralpixel = self.config.centralpixel # (column, row) = (delta, gamma)
        beta_range= -app[1] * (numpy.arange(data.shape[1]) - centralpixel[1]) + beta
        delta_range= app[0] * (numpy.arange(data.shape[0]) - centralpixel[0]) + delta

        # masking
        if self.config.maskmatrix is not None:
            if self.config.maskmatrix.shape != data.shape:
                raise errors.BackendError('The mask matrix does not have the same shape as the images')
            weights *= self.config.maskmatrix

        delta_range = delta_range[self.config.ymask]
        beta_range = beta_range[self.config.xmask]

        weights = self.apply_mask(weights, self.config.xmask, self.config.ymask)
        intensity = self.apply_mask(data, self.config.xmask, self.config.ymask)

        intensity = numpy.rot90(intensity)
        intensity = numpy.fliplr(intensity)
        intensity = numpy.flipud(intensity)

        weights = numpy.rot90(weights)
        weights = numpy.fliplr(weights)
        weights = numpy.flipud(weights)

        #polarisation correction
        delta_grid, beta_grid = numpy.meshgrid(delta_range, beta_range)
        Pver = 1 - numpy.sin(delta_grid * numpy.pi / 180.)**2 * numpy.cos(beta_grid * numpy.pi / 180.)**2
        #intensity /= Pver
 
        return intensity, weights, (wavelength, UB, beta_range, delta_range, omega, alfa, chi, phi)
Exemple #19
0
    def get_raw_img(self):
        """
		Capture an image and return an array containing the data in raw 12-bit Bayer format
		"""

        try:
            # turn camera on/off before/after capturing image
            self.cam.continuous_capture = True
            data, meta = self.cam.next()
            self.cam.continuous_capture = False

            # The camera returns the image in 16-bit data but the first 4 bits are all zero
            data = data.astype("uint16")
            data = np.right_shift(data, 4)

            # Rotate and flip the image for more natural display
            data = np.rot90(data)
            data = np.rot90(data)
            data = np.fliplr(data)

            # print('Camera type: ' + str(data.dtype))

            # if capture was successful, return True
            retval = True

        except Exception:

            # If unable to capture image, return False and no image
            print("Unable to capture image")
            retval = False
            data = None

        return data, retval
def display_mask(background, mask, title):
    plt.axis('off')
    plt.imshow(np.rot90(background), interpolation='nearest', cmap=plt.cm.gray)
    ma = np.ma.masked_equal(mask, False)
    plt.imshow(np.rot90(ma), interpolation='nearest',
              cmap=plt.cm.autumn, alpha=0.5)
    plt.title(title)
Exemple #21
0
	def get_transformed_model(self, transforms):
		t = transforms

		scaling_matrix = np.matrix([
			[t['sx']/100, 0, 0, 1],
			[0, t['sy']/100, 0, 1],
			[0, 0, t['sz']/100, 1],
			[0, 0, 0, 1]
		])

		translation_matrix = np.matrix([
			[1, 0, 0, t['tx']],
			[0, 1, 0, t['ty']],
			[0, 0, 1, t['tz']],
			[0, 0, 0, 1   ]
		])

		rotation_matrix = np.matrix(euler_matrix(
			rad(t['rx']),
			rad(t['ry']),
			rad(t['rz'])
		))

		matrix = scaling_matrix * translation_matrix * rotation_matrix

		leds_ = leds.copy()
		leds_ = np.pad(leds_, (0,1), 'constant', constant_values=1)[:-1]
		leds_ = np.rot90(leds_, 3)
		leds_ = np.dot(matrix, leds_)
		leds_ = np.rot90(leds_)
		leds_ = np.array(leds_)

		return leds_
    def back_propagation(self, x, y):
        """Propagate errors, computing the gradients of the weights and biases.
        """

        nabla_w = [np.zeros(w.shape) for w in self.weights]
        nabla_b = [np.zeros(b.shape) for b in self.biases]

        # feedforward
        output = x.reshape(28, 28, -1)
        os = [output]

        for k, W, b in zip(self.layers, self.weights, self.biases):
            output = op.add_bias(
                op.conv(output, W, stride=k[1], padding=k[2]), b)
            os.append(output)

        # Backward error propagation.
        # Restore tensor to kernels shape.
        delta = self.output_delta.reshape((28, 28, -1))

        nabla_b[-1] = op.sum(op.sum(delta, axis=0), axis=0)
        nabla_w[-1] = np.rot90(op.conv(np.rot90(os[-2], k=2), delta), k=2)

        for l in range(2, self.n_layers + 1):
            w = self.weights[-l]
            delta = op.conv(delta, np.rot90(w, k=2))

            nabla_b[-l] = op.sum(op.sum(delta, axis=0), axis=0)
            nabla_w[-l] = np.rot90(op.conv(np.rot90(os[-l - 1], k=2), delta),
                                   k=2)

        return nabla_b, nabla_w, delta
Exemple #23
0
def _axialShow(data, slice, overlay = False,
        surface = None):
    """
    similar to _coronalshow
    """
    if not overlay:
        plt.imshow(np.rot90(data[:, slice, :], k=1),
                    cmap = plt.cm.gray ,  aspect = 'auto', 
                    interpolation = 'nearest')

    if overlay: 
        overlayD = np.ma.masked_array(data, data == 0)
        if surface =='wm':
            plt.imshow(np.rot90(overlayD[:, slice, :], k=1),
                           cmap = plt.cm.Reds, vmax = 1.2, vmin = 0,
                           aspect = 'auto', 
                           interpolation = 'nearest')

        if surface == 'pial':
            plt.imshow(np.rot90(overlayD[:, slice, :], k=1),
                           cmap = plt.cm.hot, vmax = 1.2, vmin = 0,
                           aspect = 'auto', 
                           interpolation = 'nearest')


    return None
Exemple #24
0
    def _load_textures(self):
        marker_one_textures = {}
        marker_two_textures = {}

        # load images
        image_green = cv2.imread('{}green.png'.format(self.FILE_PATH))
        image_yellow = cv2.imread('{}yellow.png'.format(self.FILE_PATH))
        image_blue = cv2.imread('{}blue.png'.format(self.FILE_PATH))
        image_pink = cv2.imread('{}pink.png'.format(self.FILE_PATH))
        image_saltwash = np.rot90(cv2.imread('{}saltwash.jpg'.format(self.FILE_PATH)), 2)
        image_halo = np.rot90(cv2.imread('{}halo.jpg'.format(self.FILE_PATH)), 2)

        # load textures for marker one
        marker_one_textures[TEXTURE_FRONT] = None
        marker_one_textures[TEXTURE_RIGHT] = image_green
        marker_one_textures[TEXTURE_BACK] = image_yellow
        marker_one_textures[TEXTURE_LEFT] = image_blue
        marker_one_textures[TEXTURE_TOP] = image_pink

        # load textures for marker two
        marker_two_textures[TEXTURE_FRONT] = image_saltwash
        marker_two_textures[TEXTURE_RIGHT] = image_green
        marker_two_textures[TEXTURE_BACK] = image_halo
        marker_two_textures[TEXTURE_LEFT] = image_blue
        marker_two_textures[TEXTURE_TOP] = image_pink

        return (marker_one_textures, marker_two_textures)
Exemple #25
0
def _coronalShow(data, slice, overlay = False,
        surface = None):
    
    """
    function to plot T1 volume and pial/WM surfaces
    data: nibabel loaded numpy array
    slice: integer indicating number of the desired slice
    overlay: boolean indicating whether the data is an overlay or not
    surface: string indicating what kind of surface is overlay (wm or pial)

    """

    if not overlay:
        plt.imshow(np.rot90(data[:, :, slice], k=3),
                        cmap = plt.cm.gray ,  aspect = 'auto', 
                        interpolation = 'nearest')


    if overlay:
        overlayD = np.ma.masked_array(data, data == 0)
        if surface =='wm':
                plt.imshow(np.rot90(overlayD[:,:, slice], k=3),
                           cmap = plt.cm.Reds, vmax = 1.2, vmin = 0,
                           aspect = 'auto', 
                           interpolation = 'nearest')
        if surface == 'pial':
                plt.imshow(np.rot90(overlayD[:, :, slice], k=3),
                           cmap = plt.cm.hot, vmax = 1.2, vmin = 0,
                           aspect = 'auto', 
                           interpolation = 'nearest')
    return None
def get_boundry(pix, width, height):
        start = True
        finished = False
        north = True
        xVar = 0
        initialCoord = [1, 1]
	coord = initialCoord
        boundryArr = []
        var = 5  # number of pixels to jump accross when filtering
        while finished < 4:
        	coord = search_north_border(pix, width, height, coord, boundryArr) #starting from the north direction
               	if coord == [0,0]:
                	xVar += var
                        coord = [1, xVar]
                else:
                        boundryArr.append(coord) #if it wasn't in a bad position append it
                        pix[coord[0]][coord[1]] = 500

                if xVar >= width:
			finished += 1 #completes one more rotation
			coord = initialCoord #start from the beginning again
			np.rot90(pix) #rotate the image by 90 degrees to begin searching again
		        nextDir = 'NE' # reinitialise directions
			prevDir = ['NE', 'NE', 'NE'] # want the border to search up and away from edge first
       			temp = height
			height = width
			width = temp #change the orientation of height and width
       	pix = process_boundry(pix, width, height, boundryArr)
#	print boundryArr
	return pix
Exemple #27
0
    def get_chunk_info(self,closeFile = True):
        """Preloads region header information."""
        
        if self._locations:
            return
        
        self.openfile()

        self._chunks = None
        self._locations = [0]*32*32
        self._timestamps = []
        
        # go to the beginning of the file
        self._file.seek(0)        
        
        # read chunk location table
        locations_index = numpy.reshape(numpy.rot90(numpy.reshape(range(32*32),
                (32, 32)), -self.get_north_rotations()), -1)
        for i in locations_index:
            self._locations[i] = self._read_chunk_location()
        
        # read chunk timestamp table
        timestamp_append = self._timestamps.append
        for _ in xrange(32*32): 
            timestamp_append(self._read_chunk_timestamp())
        self._timestamps = numpy.reshape(numpy.rot90(numpy.reshape(
                self._timestamps, (32,32)),self.get_north_rotations()), -1)
 
        if closeFile:        
            self.closefile()
        return
Exemple #28
0
def strel(l,d):
	print 'strel(',l,',',d,')'
	def _get_rect_shape(l):
		if l % 2 == 0:
			l+=1
		return l,l
	w,h = _get_rect_shape(l)

	d = float(d)
	m = math.tan(math.radians(d))
	if d <= 45.0:
		x1 = w
		y1 = m*x1
		_line = line
	elif d <= 90.0:
		y1 = h
		x1 = y1 / m
		_line = line2
	elif d <= 180.0:
		output = strel(l, d-90.0)
		return np.rot90(output)

	m = np.zeros((w,h))
	x1,y1 = int(math.ceil(x1)), int(math.ceil(y1))
	for x,y in _line(0,0,x1,y1):
		m[x][y] = 1
	m = np.rot90(m)
	output = np.zeros(m.shape, dtype=np.uint8)
	output[0:w/2+1, h/2:h] = m[w/2:w+1, 0:h/2+1]
	output[w/2:w+1, 0:h/2+1] = np.rot90(output[0:w/2+1, h/2:h],2)

	return output
Exemple #29
0
def random_rotation_90(channels, gt_lbls, probs_rot_90=None):
    # Rotate by 0/90/180/270 degrees.
    # channels: list (x pathways) of np arrays [channels, x, y, z]. Whole volumes, channels of a case.
    # gt_lbls: np array of shape [x,y,z]
    # probs_rot_90: {'xy': {'0': fl, '90': fl, '180': fl, '270': fl},
    #                'yz': {'0': fl, '90': fl, '180': fl, '270': fl},
    #                'xz': {'0': fl, '90': fl, '180': fl, '270': fl} }
    if probs_rot_90 is None:
        return channels, gt_lbls
        
    for key, plane_axes in zip( ['xy', 'yz', 'xz'], [(0,1), (1,2), (0,2)] ) :
        probs_plane = probs_rot_90[key]
        
        if probs_plane is None:
            continue
        
        assert len(probs_plane) == 4 # rotation 0, rotation 90 degrees, 180, 270.
        assert channels[0].shape[1+plane_axes[0]] == channels[0].shape[1+plane_axes[1]] # +1 cause [0] is channel. Image/patch must be isotropic.
        
        # Normalize probs
        sum_p = probs_plane['0'] + probs_plane['90'] + probs_plane['180'] + probs_plane['270']
        if sum_p == 0:
            continue
        for rot_k in probs_plane:
            probs_plane[rot_k] /= sum_p # normalize p to 1.
            
        p_rot_90_x0123 = ( probs_plane['0'], probs_plane['90'], probs_plane['180'], probs_plane['270'] )
        rot_90_xtimes = np.random.choice(a=(0,1,2,3), size=1, p=p_rot_90_x0123)
        for path_idx in range(len(channels)):
            channels[path_idx] = np.rot90(channels[path_idx], k=rot_90_xtimes, axes = [axis+1 for axis in plane_axes]) # + 1 cause [0] is channels.
        gt_lbls = np.rot90(gt_lbls, k=rot_90_xtimes, axes = plane_axes)
        
    return channels, gt_lbls
Exemple #30
0
def depthwise_conv2d_python_nhwc(input_np, filter_np, stride, padding):
    """Depthwise convolution operator in nchw layout.

    Parameters
    ----------
    input_np : numpy.ndarray
        4-D with shape [batch, in_height, in_width, in_channel]

    filter_np : numpy.ndarray
        4-D with shape [filter_height, filter_width, in_channel, channel_multiplier]

    stride : list / tuple of 2 ints
        [stride_height, stride_width]

    padding : str
        'VALID' or 'SAME'

    Returns
    -------
    output_np : np.ndarray
        4-D with shape [batch, out_height, out_width, out_channel]
    """
    batch, in_height, in_width, in_channel = input_np.shape
    filter_height, filter_width, _, channel_multiplier = filter_np.shape
    if isinstance(stride, int):
        stride_h = stride_w = stride
    else:
        stride_h, stride_w = stride

    # calculate output shape
    if padding == 'VALID':
        out_channel = in_channel * channel_multiplier
        out_height = (in_height - filter_height) // stride_h + 1
        out_width = (in_width - filter_width) // stride_w + 1
        output_np = np.zeros((batch, out_height, out_width, out_channel))
        for i in range(batch):
            for j in range(out_channel):
                output_np[i, :, :, j] = signal.convolve2d(input_np[i, :, :, j//channel_multiplier], \
                    np.rot90(filter_np[:, :, j//channel_multiplier, j%channel_multiplier], 2), \
                    mode='valid')[0:(in_height - filter_height + 1):stride_h, 0:(in_width - filter_height + 1):stride_w]
    if padding == 'SAME':
        out_channel = in_channel * channel_multiplier
        out_height = np.int(np.ceil(float(in_height) / float(stride_h)))
        out_width = np.int(np.ceil(float(in_width) / float(stride_w)))
        output_np = np.zeros((batch, out_height, out_width, out_channel))
        pad_along_height = np.int(np.max((out_height - 1) * stride_h + filter_height - in_height, 0))
        pad_along_width = np.int(np.max((out_width - 1) * stride_w + filter_width - in_width, 0))
        pad_top_tvm = np.int(np.ceil(float(pad_along_height) / 2))
        pad_left_tvm = np.int(np.ceil(float(pad_along_width) / 2))
        pad_top_scipy = np.int(np.ceil(float(filter_height - 1) / 2))
        pad_left_scipy = np.int(np.ceil(float(filter_width - 1) / 2))
        index_h = pad_top_scipy - pad_top_tvm
        index_w = pad_left_scipy - pad_left_tvm
        for i in range(batch):
            for j in range(out_channel):
                output_np[i, :, :, j] = signal.convolve2d(input_np[i, :, :, j//channel_multiplier], \
                    np.rot90(filter_np[:, :, j//channel_multiplier, j%channel_multiplier], 2), \
                    mode='same')[index_h:in_height:stride_h, index_w:in_width:stride_w]

    return output_np
Exemple #31
0
        # process a frame
        frame = gb.get_screen()

        # checkpoint?
        if (time.time() - last_time) > args.write_gif_every:
            elapsed = time.strftime("%Hh %Mm %Ss",
                                    time.gmtime(time.time() - t0))
            print('time: {}, frames {:.2f}M'.format(elapsed, frames / 1e6))
            frames_to_write = args.write_gif_duration
            last_time = time.time()

        # write frames
        if frames_to_write > 0:
            fr = frame.copy()
            imgs.append(np.rot90(np.fliplr(fr)))
            frames_to_write -= 1

        # write to gif?
        if len(imgs) == args.write_gif_duration:
            write_gif(imgs, '{}_{}.gif'.format(args.rom, frames), fps=10)
            imgs = []

        # decide on the action
        a = random.randint(0, len(actions_hex) - 1)
        gb.set_keys(actions_hex[a])
        gb.next_frame_skip(args.skipframes)

        # terminate?
        if frames > args.framelimit:
            break
Exemple #32
0
    def save(self, fname=None, sigma_clip=None, render=True):
        r"""Saves a rendered image of the Scene to disk.

        Once you have created a scene, this saves an image array to disk with
        an optional filename. This function calls render() to generate an
        image array, unless the render parameter is set to False, in which case
        the most recently rendered scene is used if it exists.

        Parameters
        ----------
        fname: string, optional
            If specified, save the rendering as to the file "fname".
            If unspecified, it creates a default based on the dataset filename.
            The file format is inferred from the filename's suffix. Supported
            fomats are png, pdf, eps, and ps.
            Default: None
        sigma_clip: float, optional
            Image values greater than this number times the standard deviation
            plus the mean of the image will be clipped before saving. Useful
            for enhancing images as it gets rid of rare high pixel values.
            Default: None

            floor(vals > std_dev*sigma_clip + mean)
        render: boolean, optional
            If True, will always render the scene before saving.
            If False, will use results of previous render if it exists.
            Default: True

        Returns
        -------
            Nothing

        Examples
        --------

        >>> import yt
        >>> ds = yt.load('IsolatedGalaxy/galaxy0030/galaxy0030')
        >>>
        >>> sc = yt.create_scene(ds)
        >>> # Modify camera, sources, etc...
        >>> sc.save('test.png', sigma_clip=4)

        When saving multiple images without modifying the scene (camera,
        sources,etc.), render=False can be used to avoid re-rendering.
        This is useful for generating images at a range of sigma_clip values:

        >>> import yt
        >>> ds = yt.load('IsolatedGalaxy/galaxy0030/galaxy0030')
        >>>
        >>> sc = yt.create_scene(ds)
        >>> # save with different sigma clipping values
        >>> sc.save('raw.png')  # The initial render call happens here
        >>> sc.save('clipped_2.png', sigma_clip=2, render=False)
        >>> sc.save('clipped_4.png', sigma_clip=4, render=False)

        """
        if fname is None:
            sources = list(self.sources.values())
            rensources = [s for s in sources if isinstance(s, RenderSource)]
            # if a volume source present, use its affiliated ds for fname
            if len(rensources) > 0:
                rs = rensources[0]
                basename = rs.data_source.ds.basename
                if isinstance(rs.field, str):
                    field = rs.field
                else:
                    field = rs.field[-1]
                fname = f"{basename}_Render_{field}.png"
            # if no volume source present, use a default filename
            else:
                fname = "Render_opaque.png"
        suffix = get_image_suffix(fname)
        if suffix == "":
            suffix = ".png"
            fname = f"{fname}{suffix}"

        render = self._sanitize_render(render)
        if render:
            self.render()
        mylog.info("Saving rendered image to %s", fname)

        # We can render pngs natively but for other formats we defer to
        # matplotlib.
        if suffix == ".png":
            self._last_render.write_png(fname, sigma_clip=sigma_clip)
        else:
            from matplotlib.backends.backend_pdf import FigureCanvasPdf
            from matplotlib.backends.backend_ps import FigureCanvasPS
            from matplotlib.figure import Figure

            shape = self._last_render.shape
            fig = Figure((shape[0] / 100.0, shape[1] / 100.0))
            if suffix == ".pdf":
                canvas = FigureCanvasPdf(fig)
            elif suffix in (".eps", ".ps"):
                canvas = FigureCanvasPS(fig)
            else:
                raise NotImplementedError(f"Unknown file suffix '{suffix}'")
            ax = fig.add_axes([0, 0, 1, 1])
            ax.set_axis_off()
            out = self._last_render
            nz = out[:, :, :3][out[:, :, :3].nonzero()]
            max_val = nz.mean() + sigma_clip * nz.std()
            alpha = 255 * out[:, :, 3].astype("uint8")
            out = np.clip(out[:, :, :3] / max_val, 0.0, 1.0) * 255
            out = np.concatenate([out.astype("uint8"), alpha[..., None]],
                                 axis=-1)
            # not sure why we need rot90, but this makes the orientation
            # match the png writer
            ax.imshow(np.rot90(out), origin="lower")
            canvas.print_figure(fname, dpi=100)
Exemple #33
0
np.ravel(a=two_d_array, order='F')  # Use Fortran-style unraveling (by columns)

#Alternatively, use ndarray.flatten() to flatten a multi-dimensional into 1 dimension and return a copy of the result:
two_d_array.flatten()

#Transpose of the array
two_d_array.T

#Flip an array vertically np.flipud(), upside down :
np.flipud(two_d_array)

#Flip an array horizontally with np.fliplr(), left to right:
np.fliplr(two_d_array)

#Rotate an array 90 degrees counter-clockwise with np.rot90():
np.rot90(two_d_array, k=2)  # Number of 90 degree rotations

#Shift elements in an array along a given dimension with np.roll():
np.roll(
    a=two_d_array,
    shift=1,  # Shift elements 2 positions
    axis=1)  # In each row

np.roll(
    a=two_d_array,
    shift=2,  # Shift elements 2 positions
    axis=0)  # In each columns

#Join arrays along an axis with np.concatenate():
array_to_join = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]])
Exemple #34
0
real_samples[:, 5:8] = 100 * real_samples[:, 5:8]
idx = real_samples[:, 3] > 0
real_samples[idx, 3] = real_samples[idx, 4] - 2 * np.pi
idx = real_samples[:, 8] < 1.5
real_samples[idx, 8] = real_samples[idx, 9] + 2 * np.pi

fig, axes = plt.subplots(ndim, figsize=(20, 14), sharex=True)
labels_log = [
    r"$\frac{P_{1}}{100}$", r"$\frac{T_{1}}{1000}$", r"$\frac{K_{1}}{100}$",
    r"$\omega1$", r"$e1$", r"$\frac{P_{2}}{100}$", r"$\frac{T_{2}}{1000}$",
    r"$\frac{K_{2}}{100}$", r"$\omega2$", r"$e2$", "offset1", "offset2", "1",
    "2"
]
for i in range(ndim):
    ax = axes[i]
    ax.plot(np.rot90(sampler.chain[:, :, i], 3), "k", alpha=0.3)
    ax.set_xlim(0, sampler.chain.shape[1])
    ax.set_ylabel(labels_log[i])
    ax.yaxis.set_label_coords(-0.1, 0.5)

axes[-1].set_xlabel("step number")
plt.savefig('HD85390-2-Trace.png')
# plt.show()

import corner

labels = [
    r"$P1$", r"$T_{1}$", r"$K1$", r"$\omega1$", r"$e1$", r"$P2$", r"$T_{2}$",
    r"$K2$", r"$\omega2$", r"$e2$", "offset1", "offset2", "1", "2"
]
fig = corner.corner(real_samples,
Exemple #35
0
start_time = utl.progress('Compute exact eigenfunctions in matrix format', 0)
eigenvalues_pf_exact, eigenfunctions_pf_exact = splin.eigs(
    operator.matricize(), k=number_ev)
utl.progress('Compute exact eigenfunctions in matrix format',
             100,
             cpu_time=_time.time() - start_time)

# convert results to matrices
# ---------------------------

eigenfunctions_mat = []
eigenfunctions_mat_exact = []

for i in range(number_ev):
    eigenfunctions_mat.append(
        np.rot90(TT.full(eigenfunctions_pf[i])[:, :, 0, 0]))
    eigenfunctions_mat_exact.append(
        np.rot90(
            np.real(eigenfunctions_pf_exact[:, i]).reshape(n_states,
                                                           n_states)))
    if i > 0:
        eigenfunctions_mat[i] = eigenfunctions_mat[i] / np.amax(
            abs(eigenfunctions_mat[i]))
        eigenfunctions_mat_exact[i] = eigenfunctions_mat_exact[i] / np.amax(
            abs(eigenfunctions_mat_exact[i]))
for i in range(number_ev):
    eigenfunctions_mat.append(
        np.rot90(TT.full(eigenfunctions_km[i])[:, :, 0, 0]))
    eigenfunctions_mat[i + 3] = eigenfunctions_mat[i + 3] / np.amax(
        abs(eigenfunctions_mat[i + 3]))
Exemple #36
0
 def _get_image(self):
     image_rotated = np.fliplr(np.rot90(self.game_state.getScreenRGB(),3)) # Hack to fix the rotated image returned by ple
     return image_rotated
Exemple #37
0
def rot_volume_90(vol):
    k1, k2, k3 = np.random.randint(4, size=3)
    vol = np.rot90(vol, k=k1, axes=(0, 1))  # z
    vol = np.rot90(vol, k=k2, axes=(0, 2))  # y
    vol = np.rot90(vol, k=k3, axes=(0, 1))  # z
    return vol
Exemple #38
0
def random_transform(input, target):
    """
    The function for data augmentation. Randomly select one method among five
    transformation methods (including rotation and flip) or do not use data
    augmentation.

    Args:
        input, target : the input and target patch before data augmentation
    Return:
        input, target : the input and target patch after data augmentation
    """
    p_trans = random.randrange(8)
    if p_trans == 0:  # no transformation
        input = input
        target = target
    elif p_trans == 1:  # left rotate 90
        input = np.rot90(input, k=1, axes=(1, 2))
        target = np.rot90(target, k=1, axes=(1, 2))
    elif p_trans == 2:  # left rotate 180
        input = np.rot90(input, k=2, axes=(1, 2))
        target = np.rot90(target, k=2, axes=(1, 2))
    elif p_trans == 3:  # left rotate 270
        input = np.rot90(input, k=3, axes=(1, 2))
        target = np.rot90(target, k=3, axes=(1, 2))
    elif p_trans == 4:  # horizontal flip
        input = input[:, :, ::-1]
        target = target[:, :, ::-1]
    elif p_trans == 5:  # horizontal flip & left rotate 90
        input = input[:, :, ::-1]
        input = np.rot90(input, k=1, axes=(1, 2))
        target = target[:, :, ::-1]
        target = np.rot90(target, k=1, axes=(1, 2))
    elif p_trans == 6:  # horizontal flip & left rotate 180
        input = input[:, :, ::-1]
        input = np.rot90(input, k=2, axes=(1, 2))
        target = target[:, :, ::-1]
        target = np.rot90(target, k=2, axes=(1, 2))
    elif p_trans == 7:  # horizontal flip & left rotate 270
        input = input[:, :, ::-1]
        input = np.rot90(input, k=3, axes=(1, 2))
        target = target[:, :, ::-1]
        target = np.rot90(target, k=3, axes=(1, 2))
    return input, target
Exemple #39
0
 def rot90_3d(self, m, k=1, axis=2):
     """Rotate an array by 90 degrees in the counter-clockwise direction around the given axis"""
     m = np.swapaxes(m, 2, axis)
     m = np.rot90(m, k)
     m = np.swapaxes(m, 2, axis)
     return m
Exemple #40
0
while (line!='end'):
    if line=='':
        lineDict[int(lines[0][5:-1])]=np.array([list(item) for item in lines[1:]])
        integers.append(int(lines[0][5:-1]))
        lines=[]
    else:
        lines.append(line)
    line=input()
lineDict[int(lines[0][5:-1])]=np.array([list(item) for item in lines[1:]])
integers.append(int(lines[0][5:-1]))
lineDict2={}

for key,value in lineDict.items():
    li=[]
    li.append(value)
    li.append(np.rot90(value))
    li.append(np.rot90(value,2))
    li.append(np.rot90(value,3))
    li.append(value[::-1])
    li.append(np.rot90(value[::-1]))
    li.append(np.rot90(value[::-1],2))
    li.append(np.rot90(value[::-1],3))
    li.append(np.flip(value,1))
    li.append(np.rot90(np.flip(value,1)))
    li.append(np.rot90(np.flip(value,1),2))
    li.append(np.rot90(np.flip(value,1),3))


    
    lineDict2[key]=li
    
Exemple #41
0
    def __call__(self, image, label):
        k = random.randint(0, 3)
        image = np.rot90(image, k)

        return image, label
def rot90(W):
    for i in range(W.shape[0]):
        for j in range(W.shape[1]):
            W[i, j] = np.rot90(W[i, j], 2)
    return W
def game_state_transformer(self, game_state):
    new_game_state = copy.deepcopy(game_state)
    own_pos = game_state['self'][3]
    new_pos = list(own_pos)
    state = ""

    for i in range(len(new_game_state['bombs'])):
        new_game_state['bombs'][i] = list(new_game_state['bombs'][i])
    
    if own_pos[0] > 8:

        new_game_state['coins'] = []

        if own_pos[1] > 8:

            new_game_state['field'] = np.rot90(new_game_state['field'])
            new_game_state['field'] = np.rot90(new_game_state['field'])

            new_game_state['explosion_map'] = np.rot90(new_game_state['explosion_map'])
            new_game_state['explosion_map'] = np.rot90(new_game_state['explosion_map'])

            new_pos[0] = self.rd_x[own_pos[1] - 1][own_pos[0] - 1]
            new_pos[1] = self.rd_y[own_pos[1] - 1][own_pos[0] - 1]

            for i in range(len(game_state['coins'])):
                new_game_state['coins'].append((self.rd_x[game_state['coins'][i][1] - 1][game_state['coins'][i][0] - 1], self.rd_y[game_state['coins'][i][1] - 1][game_state['coins'][i][0] - 1]))

            for i in range(len(new_game_state['bombs'])):
                self.logger.debug(f"rotating bombs")
                new_game_state['bombs'][i][0] = (self.rd_x[new_game_state['bombs'][i][0][1] - 1][new_game_state['bombs'][i][0][0] - 1], self.rd_y[new_game_state['bombs'][i][0][1] - 1][new_game_state['bombs'][i][0][0] - 1])
            
            state = "rd"
        else:

            new_game_state['field'] = np.rot90(new_game_state['field'])
            
            

            new_game_state['explosion_map'] = np.rot90(new_game_state['explosion_map'])
            
            

            new_pos[0] = self.ru_x[own_pos[1] - 1][own_pos[0] - 1]
            new_pos[1] = self.ru_y[own_pos[1] - 1][own_pos[0] - 1]

            for i in range(len(game_state['coins'])):
                new_game_state['coins'].append((self.ru_x[game_state['coins'][i][1] - 1][game_state['coins'][i][0] - 1],self.ru_y[game_state['coins'][i][1] - 1][game_state['coins'][i][0] - 1]))

            for i in range(len(new_game_state['bombs'])):
                self.logger.debug(f"rotating bombs")
                new_game_state['bombs'][i][0] = (self.ru_x[new_game_state['bombs'][i][0][1] - 1][new_game_state['bombs'][i][0][0] - 1], self.ru_y[new_game_state['bombs'][i][0][1] - 1][new_game_state['bombs'][i][0][0] - 1])

            state = "ru"
            
            
    elif own_pos[1] > 8:
        new_game_state['coins'] = []
        
        new_game_state['field'] = np.rot90(new_game_state['field'])
        new_game_state['field'] = np.rot90(new_game_state['field'])
        new_game_state['field'] = np.rot90(new_game_state['field'])

        new_game_state['explosion_map'] = np.rot90(new_game_state['explosion_map'])
        new_game_state['explosion_map'] = np.rot90(new_game_state['explosion_map'])
        new_game_state['explosion_map'] = np.rot90(new_game_state['explosion_map'])

        new_pos[0] = self.ld_x[own_pos[1] - 1][own_pos[0] - 1]
        new_pos[1] = self.ld_y[own_pos[1] - 1][own_pos[0] - 1]

        for i in range(len(game_state['coins'])):
            new_game_state['coins'].append((self.ld_x[game_state['coins'][i][1] - 1][game_state['coins'][i][0] - 1], self.ld_y[game_state['coins'][i][1] - 1][game_state['coins'][i][0] - 1]))

        for i in range(len(new_game_state['bombs'])):
            self.logger.debug(f"rotating bombs")
            new_game_state['bombs'][i][0] = (self.ld_x[new_game_state['bombs'][i][0][1] - 1][new_game_state['bombs'][i][0][0] - 1], self.ld_y[new_game_state['bombs'][i][0][1] - 1][new_game_state['bombs'][i][0][0] - 1])

        state = "ld"

    new_game_state['self'] = list(new_game_state['self'])
    new_game_state['self'][3] = tuple(new_pos)

    return new_game_state, state
Exemple #44
0

def reshape_dataset(X, y, imsize):
    #Apply reshaping
    Xreshaped = np.array(list(map(lambda x: reshape_image(x, imsize), X)))
    #Convert to Theano-Lasagne shape
    Xreshaped = Xreshaped.reshape((Xreshaped.shape[0], 1, imsize, imsize))
    return Xreshaped, y


##Data Augmentation and Minibatch
augmentations = {
    "identity": lambda x: x,
    "flipvert": lambda x: np.flip(x, 2),
    "fliphor": lambda x: np.flip(x, 3),
    "rot90": lambda x: np.rot90(x, k=1, axes=(2, 3)),
    "rot180": lambda x: np.rot90(x, k=2, axes=(2, 3)),
    "rot270": lambda x: np.rot90(x, k=3, axes=(2, 3))
}

augmentations_state = {
    "identity": True,
    "flipvert": True,
    "fliphor": True,
    "rot90": True,
    "rot180": True,
    "rot270": True
}


def augmentation_iter(images):
Exemple #45
0
def plot_movie_semantic(semantic, image_array, acts, vals, rews, save=None):
    def getImage(act, num):
        if act == 0:
            return stand
        if num == 0:
            if act == 1:
                return up
            if act == 2:
                return down
        if num == 1:
            if act == 1:
                return turn_l
            if act == 2:
                return turn_r
        if num == 2 and act == 1:
            return jump
        if num == 3:
            if act == 1:
                return right
            if act == 2:
                return left

    jump = imageio.imread('./symbols/jump.png')
    left = imageio.imread('./symbols/arrow-left.png')
    right = imageio.imread('./symbols/arrow_right.png')
    down = imageio.imread('./symbols/down-arrow.png')
    up = imageio.imread('./symbols/up-arrow.png')
    turn_l = imageio.imread('./symbols/turn-left.png')
    turn_r = imageio.imread('./symbols/turn-right.png')
    stand = imageio.imread('./symbols/Stand.png')

    fig = plt.figure(figsize=(10, 3), dpi=72)
    ax1 = fig.add_subplot(1, 2, 1)
    plt.axis('off')
    lbls = np.rot90(
        np.array([int(n) for n in semantic[0][1:-4].split(",")]).reshape(
            (128, 128)))
    im1 = plt.imshow(lbls, vmin=-1, vmax=10, cmap='tab20')
    values = np.linspace(-1, 10, 12)
    colors = [im1.cmap(im1.norm(value)) for value in values]
    patches = [
        mpatches.Patch(color=colors[i], label=inv_map[values[i]])
        for i in range(len(values))
    ]
    plt.legend(handles=patches,
               bbox_to_anchor=(1.05, 1),
               loc=2,
               borderaxespad=0.)

    ax4 = fig.add_subplot(1, 2, 2)
    im4 = plt.imshow(image_array[0])
    plt.axis('off')
    ax3 = fig.add_subplot(6, 2, 2)
    im3 = plt.text(0.2,
                   0.1,
                   "R: " + str(rews[0]) + ' V: ' + str(vals[0]),
                   fontsize=15,
                   color='white',
                   bbox=dict(facecolor='blue', alpha=0.5))
    plt.axis('off')

    ax5 = fig.add_subplot(4, 10, 10)
    im5 = plt.imshow(getImage(acts[0][0][0], 0))
    plt.axis('off')
    ax6 = fig.add_subplot(4, 10, 20)
    im6 = plt.imshow(getImage(acts[0][0][1], 1))
    plt.axis('off')
    ax7 = fig.add_subplot(4, 10, 30)
    im7 = plt.imshow(getImage(acts[0][0][2], 2))
    plt.axis('off')
    ax8 = fig.add_subplot(4, 10, 40)
    im8 = plt.imshow(getImage(acts[0][0][3], 3))
    plt.axis('off')

    Writer = animation.writers['ffmpeg']
    writer = Writer(fps=10, metadata=dict(artist='Me'), bitrate=1800)

    def animate(i):
        try:
            lbls = np.rot90(
                np.array([int(n)
                          for n in semantic[i][1:-4].split(",")]).reshape(
                              (128, 128)))
            im1.set_array(lbls)
        except:
            broken = np.array([int(n) for n in data[i][1:-4].split(",")])
            lbls = np.rot90(
                np.append(broken,
                          np.zeros((128 * 128) - broken.shape[0])).reshape(
                              (128, 128)))
            im1.set_array(lbls)
            print(str(i) + " - " + str(broken.shape))

        im3.set_text("R: " + str(rews[i])[:3] + ' V: ' +
                     str(vals[i][0][0])[:4])
        im4.set_array(image_array[i])
        im5.set_array(getImage(acts[i][0][0], 0))
        im6.set_array(getImage(acts[i][0][1], 1))
        im7.set_array(getImage(acts[i][0][2], 2))
        im8.set_array(getImage(acts[i][0][3], 3))
        return (im1, )

    anim = animation.FuncAnimation(fig, animate, frames=len(image_array))
    display(IPython_display.display_animation(anim))
    if save != None:
        anim.save(save, writer=writer)
Exemple #46
0
Qhel_bins = 0.5 * (Qhel_edges[1:] + Qhel_edges[:-1])

fignum = 0
fig = plt.figure(fignum)

#mycmap_FES = cm.get_cmap('gist_earth')
#mycmap_FES = cm.get_cmap('OrRd_r')
#mycmap_FES = cm.get_cmap('BuPu_r')
#mycmap = cm.get_cmap('ocean')
mycmap_FES = cm.get_cmap('terrain')
#mycmap.set_over('w')
#_jet_data = {'red': ((0., 0, 0), (0.35, 0, 0), (0.66, 1, 1), (0.89,1, 1), (1, 0.5, 0.5)), 'green': ((0., 0, 0), (0.125,0, 0), (0.375,1, 1), (0.64,1, 1), (0.91,0,0), (1, 0, 0)), 'blue': ((0., 0.5, 0.5), (0.11, 1, 1), (0.34, 1, 1), (0.65,0, 0), (1, 0, 0))}
#cdict = {'red': ((0., 0, 0), (0.35, 0, 0), (0.66, 1, 1), (0.89,1, 1), (1., 1, 1)), 'green': ((0., 0, 0), (0.125,0, 0), (0.375,1, 1), (0.64,1, 1), (0.91,0,0), (1., 1, 1)), 'blue': ((0., 0.5, 0.5), (0.11, 1, 1), (0.34, 1, 1), (0.65,0, 0), (1., 1, 1))}
#mycmap = matplotlib.colors.LinearSegmentedColormap('my_colormap',cdict,256)

H_Rg_Qhel = np.rot90(H_Rg_Qhel)
H_Rg_Qhel = np.flipud(H_Rg_Qhel)

FE_H = -np.ma.log(H_Rg_Qhel)
FE_H -= np.min(FE_H)
FE_max = np.max(FE_H)
#FE_H.set_fill_value(np.max(FE_H))
FE_H = FE_H.filled()
plt.pcolormesh(Rg_bins, Qhel_bins, FE_H, cmap='terrain', vmax=FE_max)
#plt.scatter(Rg, Qhel)

#cbar = plt.colorbar()
#cbar.set_ticks([0,3,6])
#cbar.ax.set_yticklabels([r'0', r'3', r'6'],fontweight='normal')
#cbar.ax.tick_params(labelsize='32',width=4.0,length=21)
#cbar.set_label(r'$k_{\rm B} T$', rotation=270, fontsize='40', labelpad=35)
Exemple #47
0
def show_discrete_data(values,
                       grid,
                       title=None,
                       method='',
                       force_show=False,
                       fig=None,
                       **kwargs):
    """Display a discrete 1d or 2d function.

    Parameters
    ----------
    values : `numpy.ndarray`
        The values to visualize.

    grid : `RectGrid` or `RectPartition`
        Grid of the values.

    title : string, optional
        Set the title of the figure.

    method : string, optional
        1d methods:

        'plot' : graph plot

        'scatter' : scattered 2d points
        (2nd axis <-> value)

        2d methods:

        'imshow' : image plot with coloring according to value,
        including a colorbar.

        'scatter' : cloud of scattered 3d points
        (3rd axis <-> value)

        'wireframe', 'plot_wireframe' : surface plot

    force_show : bool, optional
        Whether the plot should be forced to be shown now or deferred until
        later. Note that some backends always displays the plot, regardless
        of this value.

    fig : `matplotlib.figure.Figure`, optional
        The figure to show in. Expected to be of same "style", as the figure
        given by this function. The most common usecase is that fig is the
        return value from an earlier call to this function.
        Default: New figure

    interp : {'nearest', 'linear'}, optional
        Interpolation method to use.
        Default: 'nearest'

    axis_labels : string, optional
        Axis labels, default: ['x', 'y']

    update_in_place : bool, optional
        Update the content of the figure in-place. Intended for faster real
        time plotting, typically ~5 times faster.
        This is only performed for ``method == 'imshow'`` with real data and
        ``fig != None``. Otherwise this parameter is treated as False.
        Default: False

    axis_fontsize : int, optional
        Fontsize for the axes. Default: 16

    kwargs : {'figsize', 'saveto', ...}, optional
        Extra keyword arguments passed on to display method
        See the Matplotlib functions for documentation of extra
        options.

    Returns
    -------
    fig : `matplotlib.figure.Figure`
        The resulting figure. It is also shown to the user.

    See Also
    --------
    matplotlib.pyplot.plot : Show graph plot

    matplotlib.pyplot.imshow : Show data as image

    matplotlib.pyplot.scatter : Show scattered 3d points
    """
    # Importing pyplot takes ~2 sec, only import when needed.
    import matplotlib.pyplot as plt

    args_re = []
    args_im = []
    dsp_kwargs = {}
    sub_kwargs = {}
    arrange_subplots = (121, 122)  # horzontal arrangement

    # Create axis labels which remember their original meaning
    axis_labels = kwargs.pop('axis_labels', ['x', 'y'])

    values_are_complex = not is_real_dtype(values.dtype)
    figsize = kwargs.pop('figsize', None)
    saveto = kwargs.pop('saveto', None)
    interp = kwargs.pop('interp', 'nearest')
    axis_fontsize = kwargs.pop('axis_fontsize', 16)

    # Check if we should and can update the plot in-place
    update_in_place = kwargs.pop('update_in_place', False)
    if (update_in_place
            and (fig is None or values_are_complex or values.ndim != 2 or
                 (values.ndim == 2 and method not in ('', 'imshow')))):
        update_in_place = False

    if values.ndim == 1:  # TODO: maybe a plotter class would be better
        if not method:
            if interp == 'nearest':
                method = 'step'
                dsp_kwargs['where'] = 'mid'
            elif interp == 'linear':
                method = 'plot'
            else:
                method = 'plot'

        if method == 'plot' or method == 'step' or method == 'scatter':
            args_re += [grid.coord_vectors[0], values.real]
            args_im += [grid.coord_vectors[0], values.imag]
        else:
            raise ValueError('`method` {!r} not supported' ''.format(method))

    elif values.ndim == 2:
        if not method:
            method = 'imshow'

        if method == 'imshow':
            args_re = [np.rot90(values.real)]
            args_im = [np.rot90(values.imag)] if values_are_complex else []

            extent = [
                grid.min()[0],
                grid.max()[0],
                grid.min()[1],
                grid.max()[1]
            ]

            if interp == 'nearest':
                interpolation = 'nearest'
            elif interp == 'linear':
                interpolation = 'bilinear'
            else:
                interpolation = 'none'

            dsp_kwargs.update({
                'interpolation': interpolation,
                'cmap': 'bone',
                'extent': extent,
                'aspect': 'auto'
            })
        elif method == 'scatter':
            pts = grid.points()
            args_re = [pts[:, 0], pts[:, 1], values.ravel().real]
            args_im = ([pts[:, 0], pts[:, 1],
                        values.ravel().imag] if values_are_complex else [])
            sub_kwargs.update({'projection': '3d'})
        elif method in ('wireframe', 'plot_wireframe'):
            method = 'plot_wireframe'
            x, y = grid.meshgrid
            args_re = [x, y, np.rot90(values.real)]
            args_im = ([x, y, np.rot90(values.imag)]
                       if values_are_complex else [])
            sub_kwargs.update({'projection': '3d'})
        else:
            raise ValueError('`method` {!r} not supported' ''.format(method))

    else:
        raise NotImplementedError('no method for {}d display implemented'
                                  ''.format(values.ndim))

    # Additional keyword args are passed on to the display method
    dsp_kwargs.update(**kwargs)

    if fig is not None:
        # Reuse figure if given as input
        if not isinstance(fig, plt.Figure):
            raise TypeError('`fig` {} not a matplotlib figure'.format(fig))

        if not plt.fignum_exists(fig.number):
            # If figure does not exist, user either closed the figure or
            # is using IPython, in this case we need a new figure.

            fig = plt.figure(figsize=figsize)
            updatefig = False
        else:
            # Set current figure to given input
            fig = plt.figure(fig.number)
            updatefig = True

            if values.ndim > 1 and not update_in_place:
                # If the figure is larger than 1d, we can clear it since we
                # dont reuse anything. Keeping it causes performance problems.
                fig.clf()
    else:
        fig = plt.figure(figsize=figsize)
        updatefig = False

    if values_are_complex:
        # Real
        if len(fig.axes) == 0:
            # Create new axis if needed
            sub_re = plt.subplot(arrange_subplots[0], **sub_kwargs)
            sub_re.set_title('Real part')
            sub_re.set_xlabel(axis_labels[0], fontsize=axis_fontsize)
            if values.ndim == 2:
                sub_re.set_ylabel(axis_labels[1], fontsize=axis_fontsize)
            else:
                sub_re.set_ylabel('value')
        else:
            sub_re = fig.axes[0]

        display_re = getattr(sub_re, method)
        csub_re = display_re(*args_re, **dsp_kwargs)

        # Axis ticks
        if method == 'imshow' and not grid.is_uniform:
            (xpts, xlabels), (ypts, ylabels) = _axes_info(grid)
            plt.xticks(xpts, xlabels)
            plt.yticks(ypts, ylabels)

        if method == 'imshow' and len(fig.axes) < 2:
            # Create colorbar if none seems to exist

            # Use clim from kwargs if given
            if 'clim' not in kwargs:
                minval_re, maxval_re = _safe_minmax(values.real)
            else:
                minval_re, maxval_re = kwargs['clim']

            ticks_re = _colorbar_ticks(minval_re, maxval_re)
            format_re = _colorbar_format(minval_re, maxval_re)

            plt.colorbar(csub_re,
                         orientation='horizontal',
                         ticks=ticks_re,
                         format=format_re)

        # Imaginary
        if len(fig.axes) < 3:
            sub_im = plt.subplot(arrange_subplots[1], **sub_kwargs)
            sub_im.set_title('Imaginary part')
            sub_im.set_xlabel(axis_labels[0], fontsize=axis_fontsize)
            if values.ndim == 2:
                sub_im.set_ylabel(axis_labels[1], fontsize=axis_fontsize)
            else:
                sub_im.set_ylabel('value')
        else:
            sub_im = fig.axes[2]

        display_im = getattr(sub_im, method)
        csub_im = display_im(*args_im, **dsp_kwargs)

        # Axis ticks
        if method == 'imshow' and not grid.is_uniform:
            (xpts, xlabels), (ypts, ylabels) = _axes_info(grid)
            plt.xticks(xpts, xlabels)
            plt.yticks(ypts, ylabels)

        if method == 'imshow' and len(fig.axes) < 4:
            # Create colorbar if none seems to exist

            # Use clim from kwargs if given
            if 'clim' not in kwargs:
                minval_im, maxval_im = _safe_minmax(values.imag)
            else:
                minval_im, maxval_im = kwargs['clim']

            ticks_im = _colorbar_ticks(minval_im, maxval_im)
            format_im = _colorbar_format(minval_im, maxval_im)

            plt.colorbar(csub_im,
                         orientation='horizontal',
                         ticks=ticks_im,
                         format=format_im)

    else:
        if len(fig.axes) == 0:
            # Create new axis object if needed
            sub = plt.subplot(111, **sub_kwargs)
            sub.set_xlabel(axis_labels[0], fontsize=axis_fontsize)
            if values.ndim == 2:
                sub.set_ylabel(axis_labels[1], fontsize=axis_fontsize)
            else:
                sub.set_ylabel('value')
            try:
                # For 3d plots
                sub.set_zlabel('z')
            except AttributeError:
                pass
        else:
            sub = fig.axes[0]

        if update_in_place:
            import matplotlib as mpl
            imgs = [
                obj for obj in sub.get_children()
                if isinstance(obj, mpl.image.AxesImage)
            ]
            if len(imgs) > 0 and updatefig:
                imgs[0].set_data(args_re[0])
                csub = imgs[0]

                # Update min-max
                if 'clim' not in kwargs:
                    minval, maxval = _safe_minmax(values)
                else:
                    minval, maxval = kwargs['clim']

                csub.set_clim(minval, maxval)
            else:
                display = getattr(sub, method)
                csub = display(*args_re, **dsp_kwargs)
        else:
            display = getattr(sub, method)
            csub = display(*args_re, **dsp_kwargs)

        # Axis ticks
        if method == 'imshow' and not grid.is_uniform:
            (xpts, xlabels), (ypts, ylabels) = _axes_info(grid)
            plt.xticks(xpts, xlabels)
            plt.yticks(ypts, ylabels)

        if method == 'imshow':
            # Add colorbar
            # Use clim from kwargs if given
            if 'clim' not in kwargs:
                minval, maxval = _safe_minmax(values)
            else:
                minval, maxval = kwargs['clim']

            ticks = _colorbar_ticks(minval, maxval)
            format = _colorbar_format(minval, maxval)
            if len(fig.axes) < 2:
                # Create colorbar if none seems to exist
                plt.colorbar(mappable=csub, ticks=ticks, format=format)
            elif update_in_place:
                # If it exists and we should update it
                csub.colorbar.set_clim(minval, maxval)
                csub.colorbar.set_ticks(ticks)
                csub.colorbar.set_ticklabels([format % tick for tick in ticks])
                csub.colorbar.draw_all()

    # Set title of window
    if title is not None:
        if not values_are_complex:
            # Do not overwrite title for complex values
            plt.title(title)
        fig.canvas.manager.set_window_title(title)

    # Fixes overlapping stuff at the expense of potentially squashed subplots
    if not update_in_place:
        fig.tight_layout()

    if updatefig or plt.isinteractive():
        # If we are running in interactive mode, we can always show the fig
        # This causes an artifact, where users of `CallbackShow` without
        # interactive mode only shows the figure after the second iteration.
        plt.show(block=False)
        if not update_in_place:
            plt.draw()
            warning_free_pause()
        else:
            try:
                sub.draw_artist(csub)
                fig.canvas.blit(fig.bbox)
                fig.canvas.update()
                fig.canvas.flush_events()
            except AttributeError:
                plt.draw()
                warning_free_pause()

    if force_show:
        plt.show()

    if saveto is not None:
        fig.savefig(saveto)
    return fig
Exemple #48
0
def main():
    img = read_image('1.jpg')
    img = np.rot90(img)
    img = np.rot90(img)
    img = np.rot90(img)
    write_image('2.jpg', img)
Exemple #49
0
 Label = np.median(
     CroppedClassRaster[y:y + size, x:x + size].reshape(1, -1)
 )  #Class expressed as a single number for an individual tile.
 Valid = CheckLabel(LabelTile)
 Tile = np.int16(im[y:y + size,
                    x:x + size, :].reshape(size, size,
                                           d))  #Image tile.
 #Tile = np.uint8(255*Tile/16384)
 if Valid:  #==true i.e. if the tile has a dominant class assigned to it.
     #raw tile
     I = np.uint16(Tile)
     save_tile(I, Label, CurrentTile, DataFolder, size,
               stride)  #Save the tile to disk.
     CurrentTile += 1  #Current tile plus 1 - so won't overwrite previously saved file.
     #90 rotation + noise.
     Tile = np.rot90(Tile)
     I = Tile + np.random.randint(
         low=-10, high=+10, size=Tile.shape
     )  #Rotates tile 90 degrees + noise from -10 to 10.
     save_tile(np.uint16(I), Label, CurrentTile, DataFolder, size,
               stride)  #Save the tile to disk.
     CurrentTile += 1  #Saves rotated tile and does not overwrite previously saved files.
     #180 rotation + noise.
     Tile = np.rot90(Tile)
     I = Tile + np.random.randint(
         low=-10, high=+10, size=Tile.shape
     )  ##Rotates tile 90 degrees + noise from -10 to 10.
     save_tile(np.uint16(I), Label, CurrentTile, DataFolder, size,
               stride)  #Save the tile to disk.
     CurrentTile += 1  #Saves rotated tile and does not overwrite previously saved files.
     #270 rotation + noise.
 def test_axes(self):
     a = ones((50, 40, 3))
     assert_equal(rot90(a).shape, (40, 50, 3))
Exemple #51
0
        face_inrange = cv2.inRange(face_hsv, hsv_min, hsv_max)
        face_inrange = np.array([[[v, v, v] for v in row]
                                 for row in face_inrange],
                                dtype=bool)
        #print 'face_inrange: %s - %s' % (face_inrange.shape, face_inrange.dtype)

        pres_skin = [0.2, 0.65, 1.7]
        face_bgr = frame[y:y + h, x:x + w, :] * pres_skin
        face_bgr = np.minimum(face_bgr, 255)
        face_bgr = np.array(face_bgr, dtype='uint8')
        #print 'face_bgr: %s - %s' % (face_bgr.shape, face_bgr.dtype)
        np.copyto(frame[y:y + h, x:x + w, :], face_bgr, where=face_inrange)

        # More presidential hair
        hair = sq[30:, 0:70]
        hair = np.rot90(hair, 3)
        hair_mask = sq_mask[30:, 0:70]
        hair_mask = np.rot90(hair_mask, 3)

        hair_scale = w0 / float(hair.shape[1])

        hair = cv2.resize(hair, None, fx=hair_scale, fy=hair_scale)

        hair_mask = np.array(hair_mask, dtype='uint8')
        hair_mask = cv2.resize(hair_mask, None, fx=hair_scale, fy=hair_scale)
        hair_mask = np.array(hair_mask, dtype=bool)

        hair = np.array(np.minimum((hair * 0.7) + 100, 255),
                        dtype='uint8')  # Optional

        if y0 - hair.shape[0] < 0:
Exemple #52
0
                    y[i, j] += kernal[a, b] * img[i + a, j + b]
    return y


img = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) * 1.0
k = np.array([[1, 2], [2, 3]]) * 1.0

# img = np.random.randn(150, 150)
# k = np.random.randn(9, 7)

t = time.time()
_conv2d(img, k)
print 'python:', time.time() - t

t = time.time()
convolution.conv2d(img, k)
print 'cython:', time.time() - t

t = time.time()
convolution.deconv2d(img, k)
print 'deconv:', time.time() - t

t = time.time()
convolve2d(img, np.rot90(k, 2), mode='valid')
print 'scipy:', time.time() - t

c = convolution.conv2d(img, k)
print c
print convolve2d(img, np.rot90(k, 2), mode='valid')
print convolution.deconv2d(c, k)
print k
Exemple #53
0
def plot_on_kite_box(coords_out,
                     coords_line,
                     scene,
                     eastings,
                     northings,
                     eastcomb,
                     northcomb,
                     x0c,
                     y0c,
                     x1c,
                     y1c,
                     name,
                     ellipses,
                     mind,
                     maxd,
                     fname,
                     synthetic=False,
                     topo=False):
    '''
    Plotting function for plotting a rectangle from coords_out and coords_line
    with coordinates eastings and northings on data from a kite scene withhin
    frame given by x0, y0, x1 and y1 and saves
    the image to a folder under name fname. Optional draw of topography.
    '''
    scd = scene
    data_dsc = scd.displacement
    lengths = []
    widths = []

    data_dsc[data_dsc == 0] = num.nan
    extent = [
        num.min(eastings),
        num.max(eastings),
        num.min(northings),
        num.max(northings)
    ]
    central_lon = num.mean(extent[:2])
    central_lat = num.mean(extent[2:])
    f, ax = plt.subplots(1, 1, subplot_kw=dict(projection=ccrs.PlateCarree()))
    ax.set_extent(extent)

    if topo is True:
        # shade function when the data is retrieved.
        shaded_srtm = PostprocessedRasterSource(SRTM1Source(), shade)
        # Add the shaded SRTM source to our map with a grayscale colormap.
        ax.add_raster(shaded_srtm, cmap='Greys')
        ax.add_feature(cartopy.feature.OCEAN)
        ax.add_feature(cartopy.feature.LAND, edgecolor='black')
        ax.add_feature(cartopy.feature.LAKES, edgecolor='black')
        ax.add_feature(cartopy.feature.RIVERS)

    scale_bar(ax, (0.1, 0.1), 5_0)
    h = ax.imshow(num.rot90(data_dsc.T),
                  origin='upper',
                  extent=extent,
                  transform=ccrs.PlateCarree(),
                  cmap="seismic",
                  vmin=mind,
                  vmax=maxd,
                  alpha=0.8,
                  norm=MidpointNormalize(mind, maxd, 0.))

    ax.gridlines(draw_labels=True)

    coords_all = []
    for coords in coords_line:
        coords_boxes = []
        for k in coords:
            kx = k[1]
            ky = k[0]
            coords_boxes.append(
                [eastcomb[int(kx)][int(ky)], northcomb[int(kx)][int(ky)]])
        coords_all.append(coords_boxes)
    n = 0
    for coords, ell in zip(coords_all, ellipses):

        x1, y1 = coords[0][0], coords[0][1]
        x1a, y1a = coords[1][0], coords[1][1]
        x0, y0 = coords[2][0], coords[2][1]
        x2, y2 = coords[3][0], coords[3][1]
        n = n + 1
        ax.plot((x0, x1), (y0, y1), 'r--', linewidth=2.5)
        ax.plot((x0, x1a), (y0, y1a), 'r--', linewidth=2.5)

        ax.plot((x0, x2), (y0, y2), '-r', linewidth=2.5)
        ax.plot(x0, y0, '.g', markersize=15)
        height = orthodrome.distance_accurate50m(coords[0][0], coords[0][1],
                                                 coords[3][0], coords[3][1])
        width = orthodrome.distance_accurate50m(coords[2][0], coords[2][1],
                                                coords[3][0], coords[3][1])
        lengths.append(height)
        widths.append(width)
        e = mpatches.Ellipse((x0, y0),
                             width=width * 2.,
                             height=height * 2.,
                             angle=num.rad2deg(ell[4]) + 90,
                             lw=2,
                             edgecolor='purple',
                             fill=False)
        ax.add_patch(e)

    coords_boxes = []
    for k in coords_out:
        minr, minc, maxr, maxc = k[0], k[1], k[2], k[3]

        kx = k[2]
        ky = k[1]
        coords_boxes.append(
            [eastcomb[int(kx)][int(ky)], northcomb[int(kx)][int(ky)]])
        kx = k[0]
        ky = k[3]
        coords_boxes.append(
            [eastcomb[int(kx)][int(ky)], northcomb[int(kx)][int(ky)]])

    n = 0

    for coords in coords_out:
        minc, minr = coords_boxes[0 + n][0], coords_boxes[0 + n][1]
        maxc, maxr = coords_boxes[1 + n][0], coords_boxes[1 + n][1]

        n = n + 2
        rect = mpatches.Rectangle((minc, minr),
                                  maxc - minc,
                                  maxr - minr,
                                  fill=False,
                                  edgecolor='r',
                                  linewidth=2)
        ax.add_patch(rect)

    try:
        parallels = num.linspace(y0c, y1c, 22)
        meridians = num.linspace(x0c, x1c, 22)
    except:
        parallels = num.linspace((num.min(northings)), (num.max(northings)),
                                 22)
        meridians = num.linspace((num.min(eastings)), (num.max(eastings)), 22)

    if synthetic is True:
        from pyrocko.gf import RectangularSource

        srcs = load_all(filename='%s.yml' % name)

        for source in srcs:
            n, e = source.outline(cs='latlon').T
            ax.fill(e, n, color=(0, 0, 0), lw=3)

    addArrow(ax, scene)

    gl = ax.gridlines(draw_labels=True)
    gl.ylabels_right = False
    gl.xlabels_top = False
    addArrow(ax, scene)
    divider = make_axes_locatable(ax)
    cax = divider.new_horizontal(size="5%", pad=0.1, axes_class=plt.Axes)
    f.add_axes(cax)
    plt.colorbar(h, cax=cax)

    fig = plt.gcf()
    fig.set_size_inches((11, 11), forward=False)
    plt.savefig(fname + 'box.svg', format='svg', dpi=300)
    plt.close()

    return widths, lengths
Exemple #54
0
import numpy as np

arr = np.random.randint(0, 10, size=(10, 10))

print(arr)

new_arr = np.rot90(arr, 1)

print(new_arr)
Exemple #55
0
def plot_on_kite_scatter(db,
                         scene,
                         eastings,
                         northings,
                         x0,
                         y0,
                         x1,
                         y1,
                         mind,
                         maxd,
                         fname,
                         synthetic=False,
                         topo=False):
    '''
    Plotting function for plotting scatter points from a database (db)
    with coordinates eastings and northings on data from a kite scene withhin
    frame given by x0, y0, x1 and y1 and saves
    the image to a folder under name fname. Optional draw of topography.
    '''
    scd = scene
    data_dsc = scd.displacement

    data_dsc[data_dsc == 0] = num.nan

    extent = [
        num.min(eastings),
        num.max(eastings),
        num.min(northings),
        num.max(northings)
    ]
    central_lon = num.mean(extent[:2])
    central_lat = num.mean(extent[2:])
    f, ax = plt.subplots(1, 1, subplot_kw=dict(projection=ccrs.PlateCarree()))
    ax.set_extent(extent)
    if topo is True:
        # shade function when the data is retrieved.
        shaded_srtm = PostprocessedRasterSource(SRTM1Source(), shade)
        # Add the shaded SRTM source to our map with a grayscale colormap.
        ax.add_raster(shaded_srtm, cmap='Greys')
        ax.add_feature(cartopy.feature.OCEAN)
        ax.add_feature(cartopy.feature.LAND, edgecolor='black')
        ax.add_feature(cartopy.feature.LAKES, edgecolor='black')
        ax.add_feature(cartopy.feature.RIVERS)

    h = ax.imshow(num.rot90(data_dsc.T),
                  origin='upper',
                  extent=extent,
                  transform=ccrs.PlateCarree(),
                  cmap="seismic",
                  alpha=0.8,
                  norm=MidpointNormalize(mind, maxd, 0.))

    gl = ax.gridlines(draw_labels=True)
    gl.ylabels_right = False
    gl.xlabels_top = False
    addArrow(ax, scene)
    divider = make_axes_locatable(ax)
    cax = divider.new_horizontal(size="5%", pad=0.1, axes_class=plt.Axes)
    f.add_axes(cax)
    plt.colorbar(h, cax=cax)

    gj = db
    faults = gj['features']
    coords = [feat['geometry']['coordinates'] for feat in faults]

    i = len(coords)
    colors = iter(cm.rainbow(num.linspace(0, 1, i)))
    for j in coords:
        coords_re_x = []
        coords_re_y = []
        for k in j:
            coords_re_x.append(k[0])
            coords_re_y.append(k[1])
        x, y = coords_re_x, coords_re_y
        plt.scatter(x, y, c=next(colors))

    plt.grid()

    addArrow(ax, scene)
    try:
        x0, y0 = map(x0, y0)
        x1, y1 = map(x1, y1)
        ax.set_xlim([x0, x1])
        ax.set_ylim([y0, y1])
    except:
        pass
    divider = make_axes_locatable(ax)
    try:
        plt.colorbar(cax=cax)
    except TypeError:
        pass
    fig = plt.gcf()
    fig.set_size_inches((11, 11), forward=False)
    plt.savefig(fname + 'scatter.svg', format='svg', dpi=300)
    plt.close()
Exemple #56
0
def plot_on_map(db,
                scene,
                eastings,
                northings,
                x0,
                y0,
                x1,
                y1,
                mind,
                maxd,
                fname,
                synthetic=False,
                topo=False,
                kite_scene=False,
                comb=False):

    if kite_scene is True:
        scd = scene
        data_dsc = scd.displacement
    else:
        data_dsc = num.rot90(scene.T)

    if comb is True:
        data_dsc[data_dsc < num.max(data_dsc) * 0.1] = num.nan

    else:
        data_dsc[data_dsc == 0] = num.nan

    extent = [
        num.min(eastings),
        num.max(eastings),
        num.min(northings),
        num.max(northings)
    ]
    central_lon = num.mean(extent[:2])
    central_lat = num.mean(extent[2:])
    f, ax = plt.subplots(1, 1, subplot_kw=dict(projection=ccrs.PlateCarree()))
    ax.set_extent(extent)

    if topo is True:
        # shade function when the data is retrieved.
        shaded_srtm = PostprocessedRasterSource(SRTM1Source(), shade)
        # Add the shaded SRTM source to our map with a grayscale colormap.
        ax.add_raster(shaded_srtm, cmap='Greys')
        ax.add_feature(cartopy.feature.OCEAN)
        ax.add_feature(cartopy.feature.LAND, edgecolor='black')
        ax.add_feature(cartopy.feature.LAKES, edgecolor='black')
        ax.add_feature(cartopy.feature.RIVERS)
    scale_bar(ax, (0.1, 0.1), 5_0)

    h = ax.imshow(num.rot90(data_dsc.T),
                  origin='upper',
                  extent=extent,
                  transform=ccrs.PlateCarree(),
                  cmap="seismic",
                  vmin=mind,
                  vmax=maxd,
                  alpha=0.8)

    if kite_scene is True:
        addArrow(ax, scene)

    gl = ax.gridlines(draw_labels=True)
    gl.ylabels_right = False
    gl.xlabels_top = False
    divider = make_axes_locatable(ax)
    cax = divider.new_horizontal(size="5%", pad=0.1, axes_class=plt.Axes)
    f.add_axes(cax)
    plt.colorbar(h, cax=cax)

    fig = plt.gcf()
    fig.set_size_inches((11, 11), forward=False)
    plt.savefig(fname + '.svg', format='svg', dpi=300)
    plt.close()
def set_vision_sensor_image(client_id, display_name, image, convert=None, scale_factor=256000.0, operation_mode=vrep.simx_opmode_oneshot_wait):
    """Display vision sensor image data in a V-REP simulation.
    [V-REP Vision Sensors](http://www.coppeliarobotics.com/helpFiles/en/visionSensors.htm)
    [simSetVisionSensorImage](http://www.coppeliarobotics.com/helpFiles/en/apiFunctions.htm#simSetVisionSensorImage)
    # Arguments
    display_name: the string display name of the sensor object in the v-rep scene
    image: an rgb char array containing an image
    convert: Controls how images are displayed. Options are:
            None: Do not modify the data and display it as-is for rgb input data (not working properly for float depth).
            'depth_rgb': convert a floating point depth image to a straight 0-255 encoding of depths less than 3m
            'depth_encoded_rgb': convert a floating point depth image to the rgb encoding used by
                the google brain robot data grasp dataset's raw png depth image encoding,
                see https://sites.google.com/site/brainrobotdata/home/depth-image-encoding.
            'vrep': add a vrep prefix to any of the above commands to
                rotate image by 180 degrees, flip left over right, then invert the color channels
                after the initial conversion step.
                This is due to a problem where V-REP seems to display images differently.
                Examples include 'vrep_depth_rgb' and 'vrep_depth_encoded_rgb',
                see http://www.forum.coppeliarobotics.com/viewtopic.php?f=9&t=737&p=27805#p27805.
    """
    strings = [display_name]
    parent_handle = -1

    # TODO(ahundt) support is_greyscale True again
    is_greyscale = 0
    vrep_conversion = False
    if convert is not None:
        vrep_conversion = 'vrep' in convert

        if 'depth_encoded_rgb' in convert:
            image = np.array(FloatArrayToRgbImage(image, scale_factor=scale_factor, drop_blue=False), dtype=np.uint8)
        elif 'depth_rgb' in convert:

            image = img_as_uint(image)

        elif not vrep_conversion:
            raise ValueError('set_vision_sensor_image() convert parameter must be one of `depth_encoded_rgb`, `depth_rgb`, or None'
                             'with the optional addition of the word `vrep` to rotate 180, flip left right, then invert colors.')

    if vrep_conversion:
        # rotate 180 degrees, flip left over right, then invert the colors
        image = np.array(256 - np.fliplr(np.rot90(image, 2)), dtype=np.uint8)

    if np.issubdtype(image.dtype, np.integer):
        is_float = 0
        floats = []
        color_buffer = bytearray(image.flatten().tobytes())
        color_size = image.size
        num_floats = 0
    else:
        is_float = 1
        floats = [image]
        color_buffer = bytearray()
        num_floats = image.size
        color_size = 0

    cloud_handle = -1
    res, ret_ints, ret_floats, ret_strings, ret_buffer = vrep.simxCallScriptFunction(
        client_id,
        'remoteApiCommandServer',
        vrep.sim_scripttype_childscript,
        'setVisionSensorImage_function',
        [parent_handle, num_floats, is_greyscale, color_size],  # int params
        np.append(floats, []),  # float params
        strings,  # string params
        # byte buffer params
        color_buffer,
        operation_mode)
    if res == vrep.simx_return_ok:
        print ('point cloud handle: ', ret_ints[0])  # display the reply from V-REP (in this case, the handle of the created dummy)
        # set the transform for the point cloud
        return ret_ints[0]
    else:
        print('insertPointCloud_function remote function call failed.')
        print(''.join(traceback.format_stack()))
        return res
Exemple #58
0
def plot_on_kite_line(coords_out,
                      scene,
                      eastings,
                      northings,
                      eastcomb,
                      northcomb,
                      x0c,
                      y0c,
                      x1c,
                      y1c,
                      mind,
                      maxd,
                      fname,
                      synthetic=False,
                      topo=False):
    '''
    Plotting function for plotting a line from coordinates coords_out,
    with coordinates eastings and northings on data from a kite scene withhin
    frame given by x0c, y0c, x1c and y1c and saves
    the image to a folder under name fname. Optional draw of topography.
    '''
    scd = scene
    data_dsc = scd.displacement

    data_dsc[data_dsc == 0] = num.nan
    extent = [
        num.min(eastings),
        num.max(eastings),
        num.min(northings),
        num.max(northings)
    ]
    central_lon = num.mean(extent[:2])
    central_lat = num.mean(extent[2:])
    f, ax = plt.subplots(1, 1, subplot_kw=dict(projection=ccrs.PlateCarree()))
    ax.set_extent(extent)

    if topo is True:
        # shade function when the data is retrieved.
        shaded_srtm = PostprocessedRasterSource(SRTM1Source(), shade)
        # Add the shaded SRTM source to our map with a grayscale colormap.
        ax.add_raster(shaded_srtm, cmap='Greys')
        ax.add_feature(cartopy.feature.OCEAN)
        ax.add_feature(cartopy.feature.LAND, edgecolor='black')
        ax.add_feature(cartopy.feature.LAKES, edgecolor='black')
        ax.add_feature(cartopy.feature.RIVERS)

    scale_bar(ax, (0.1, 0.1), 5_0)
    h = ax.imshow(num.rot90(data_dsc.T),
                  origin='upper',
                  extent=extent,
                  transform=ccrs.PlateCarree(),
                  cmap="seismic",
                  vmin=mind,
                  vmax=maxd,
                  alpha=0.8)

    ax.gridlines(draw_labels=True)

    coords_all = []
    for coords in coords_out:

        coords_boxes = []
        for k in coords:
            kx = k[1]
            ky = k[0]
            coords_boxes.append(
                [eastcomb[int(kx)][int(ky)], northcomb[int(kx)][int(ky)]])
        coords_all.append(coords_boxes)
    n = 0

    for coords in coords_all:

        x1, y1 = coords[0][0], coords[0][1]
        x1a, y1a = coords[1][0], coords[1][1]
        x0, y0 = coords[2][0], coords[2][1]
        x2, y2 = coords[3][0], coords[3][1]
        n = n + 1
        ax.plot((x0, x1), (y0, y1), '-r', linewidth=2.5)
        ax.plot((x0, x1a), (y0, y1a), '-r', linewidth=2.5)

        ax.plot((x0, x2), (y0, y2), '-r', linewidth=2.5)
        ax.plot(x0, y0, '.g', markersize=15)

    gl = ax.gridlines(draw_labels=True)
    gl.ylabels_right = False
    gl.xlabels_top = False
    addArrow(ax, scene)
    divider = make_axes_locatable(ax)
    cax = divider.new_horizontal(size="5%", pad=0.1, axes_class=plt.Axes)
    f.add_axes(cax)
    plt.colorbar(h, cax=cax)

    addArrow(ax, scene)

    fig = plt.gcf()
    fig.set_size_inches((11, 11), forward=False)
    plt.savefig(fname + 'line.svg', format='svg', dpi=300)
    plt.close()
Exemple #59
0
def Tetris_function(old_time):

    # Defining the board height, width
    # and initial score.
    height = 25
    width = 13
    score = 0

    # Defining the initial conditions of
    # the game.
    not_dead = True
    next_block = True

    # Change the print statement to always print on one line
    # regardless of how long it is.
    np.set_printoptions(linewidth=np.inf)

    # Creating the object: The_board and generating the matrix
    # on wich the game will be played.
    The_board = board(height, width)
    board_matrix = The_board.generate_board()

    # A loop in wich the game is played.  While this statement
    # is True the game will continue.
    while not_dead == True:

        # Wait the desired time.  This makes the game run at a
        # more consistant pase.
        time.sleep(0.0001)

        # A time statement for when the loop passes
        other_time = time.time()

        # Check difference in the two time statements
        check_time = other_time - old_time

        # The condidtions on wich a new piece is to be made
        if next_block == True:

            # Calling the function next_peice() and creating the object: "new_shape"
            next_piece = The_board.next_piece()
            new_shape = shape()

            # Depending on the value of "next_piece" a different peice will be chosen
            # created in the form of new_piece, and its identity will be aducted acordingly.
            if next_piece == "Long":
                new_piece = new_shape.Long_block()
                new_piece_identity = new_shape.get_identity() + 1
            elif next_piece == "L-left":
                new_piece = new_shape.L_left_block()
                new_piece_identity = new_shape.get_identity() + 2
            elif next_piece == "L-right":
                new_piece = new_shape.L_right_block()
                new_piece_identity = new_shape.get_identity() + 3
            elif next_piece == "Square":
                new_piece = new_shape.Square_block()
                new_piece_identity = new_shape.get_identity() + 4
            elif next_piece == "Z-left":
                new_piece = new_shape.Z_right_block()
                new_piece_identity = new_shape.get_identity() + 5
            elif next_piece == "Z-right":
                new_piece = new_shape.Z_left_block()
                new_piece_identity = new_shape.get_identity() + 6
            else:
                new_piece = new_shape.T_block()
                new_piece_identity = new_shape.get_identity() + 7

            # Now that the piece has been chosen and the identity saved,
            # the object: "new_shape" is deleted to revent memory clutter
            del new_shape

            # Defining the center of the new piece
            shape_center = [1, int(The_board.get_width() / 2)]

            # Inserting the new piece in the board
            new_board = The_board.insert_piece(new_piece, shape_center,
                                               board_matrix)

            # Parcing out the pieces of the return statement "insert_piece()"
            board_matrix = new_board[0]
            piece_position = new_board[1]
            landed = new_board[2]

            # If the new piece can not be laned than the board is deleted
            # and the program ends.
            if landed == False:
                print("Cant place new piece, you lose")
                del The_board
                sys.exit()

            # Renaming next_piece as it is now the current piece
            # and setting the condition to insert a new piece to False
            current_piece_name = next_piece
            next_block = False

        # Clearing the terminal
        os.system('cls')

        # Printing the board in a READABLE fashion and the score.
        The_board.print_board(board_matrix)
        print()
        print("Score: ", score)

        # If you wish to see what the board actualy looks like than uncoment the line below
        #The_board.print_hidden_board(board_matrix)

        # Used try so that if user pressed other than the given key error will not be shown
        try:

            # If key defined key is pressed is pressed
            if keyboard.is_pressed('a'):
                user_input = "a"
            elif keyboard.is_pressed('s'):
                user_input = "s"
            elif keyboard.is_pressed('d'):
                user_input = "d"
            elif keyboard.is_pressed('w'):
                user_input = "w"

                # The square does not rotate so it is skeipped
                # if the player tries to rotate it.
                if next_piece == "Square":
                    continue

                # Attempt to rotate the piece if possible
                try:
                    # Create a copy of the board
                    pre_matrix = np.copy(board_matrix)

                    # Parse out the height and width
                    shape_height_cord, shape_width_cord = [
                        piece_position[0], piece_position[1]
                    ], [piece_position[2], piece_position[3]]

                    # Create a new piece with the shape of the piece in question
                    pre_rot_piece = np.copy(
                        pre_matrix[shape_height_cord[0]:shape_height_cord[1],
                                   shape_width_cord[0]:shape_width_cord[1]])

                    # Rotate the new piece
                    rot_piece = np.rot90(pre_rot_piece)

                    # Wall is used as a catch all to make sure nothing overlaps
                    wall = False

                    # Inside the defined dimentions of the copied board
                    for y in range(shape_height_cord[0], shape_height_cord[1]):
                        for x in range(shape_width_cord[0],
                                       shape_width_cord[1]):

                            # If this is one of the parts of the piece, set it to
                            # "empty_space()".
                            if pre_matrix[y][x] == str(new_piece_identity):
                                pre_matrix[y][x] = The_board.get_dead_space()

                            #if the cordinates are not part of the piece and not "dead_space"
                            if pre_matrix[y][x] != The_board.get_dead_space():

                                # Wall is set to True and the inner most "try" stament is failed
                                wall = True
                                print("You cant do that.")
                                print(
                                    "You are either against the wall or agains another piece."
                                )
                                sys.exit()

                    # If there is nothing else in the piece position
                    if wall == False:

                        # Insert the rotated piece in the copied matrix
                        rot_matrix = The_board.insert_piece(
                            rot_piece, shape_center, pre_matrix)

                        # Parsing out the pieces of "insert_piece()"
                        board_matrix = rot_matrix[0]
                        piece_position = rot_matrix[1]

                        # Correcting the center of the piece depending on what
                        # the piece is.
                        if current_piece_name == "Long":
                            shape_center = rot_matrix[3]

                        elif current_piece_name == "L-left":
                            shape_center = rot_matrix[3]
                            shape_center = [
                                shape_center[0] + 1, shape_center[1]
                            ]

                        elif current_piece_name == "L-right":
                            shape_center = rot_matrix[3]
                            shape_center = [
                                shape_center[0] + 1, shape_center[1]
                            ]

                        elif current_piece_name == "Z-left":
                            shape_center = rot_matrix[3]
                            shape_center = [shape_center[0], shape_center[1]]

                        elif current_piece_name == "Z-right":
                            shape_center = rot_matrix[3]
                            shape_center = [shape_center[0], shape_center[1]]

                        else:
                            shape_center = rot_matrix[3]

                    # The old board is maintained
                    else:
                        board_matrix = board_matrix

                # If the piece could not be inserted pass
                except:
                    pass

            # If the useer does not press any buttons than
            # their input is defaled to ""
            else:
                user_input = ""

        # If the user presses anything other than "w", "a", "s", or, "d" print()
        except:
            print("Use -w-a-s-d- to move")

        # Depending on what the user inputs  the piece is moved accoringly
        check_move = The_board.move_piece(shape_center, new_piece_identity,
                                          piece_position, user_input,
                                          board_matrix)

        # Parsing out the pieces of "move_shape()"
        shape_center = check_move[3]
        board_matrix = check_move[2]
        piece_position = check_move[1]

        # Check if 2 time statemnts from above are more than
        # 2 seconds apart.
        if check_time >= 2:

            # Reset old time
            old_time = time.time()

            # Move the piece down one
            check_fall = The_board.move_piece(shape_center, new_piece_identity,
                                              piece_position, "s",
                                              board_matrix)

            # Parsing out the pieces of "move_piece()"
            shape_center = check_fall[3]
            board_matrix = check_fall[2]
            piece_position = check_fall[1]
            landed = check_fall[0]

            # Check if the piece has landed
            if landed == True:

                # Call the funtion "clear_line()" which clears any full lines
                # and shifts everything on the board down one
                board_clear = The_board.clear_line(board_matrix)

                # Parsing out the pieces of "clear_line()"
                board_matrix = board_clear[0]

                # Updating the score if nessesary
                if board_clear[1] == True:
                    score = score + 100 * board_clear[2]

                # Saying that the next block is to be called
                next_block = True

                # Shifting though each column of the board
                highest_stack = 0
                for index in range(width):
                    if (index == 0) or (index == width - 1):
                        continue

                    # Calling the function "get_stack()" which returns the given column
                    stack = The_board.get_stack(index, board_matrix)

                    # Calling the function "measure_stack()" which returns the height of the column
                    stack_height = The_board.measure_stack(stack)

                    # Record the highest stack size
                    if stack_height > highest_stack:
                        highest_stack = stack_height

                    # Call the function "check_full()" to see if the player is dead or not
                    not_dead = The_board.check_full(highest_stack)

                    # If the player is dead than the the fallowing print statment is shown.
                    if not_dead == False:
                        print("board is full, You lose :(")
    return
Exemple #60
0
def plot_process(longs,
                 lats,
                 scene,
                 ls_dark,
                 ls_clear,
                 grad_mask,
                 image,
                 grad,
                 plt_img,
                 coh_filt,
                 fname,
                 topo=False):
    eastings = longs
    northings = lats
    fig = plt.figure()

    extent = [
        num.min(eastings),
        num.max(eastings),
        num.min(northings),
        num.max(northings)
    ]
    central_lon = num.mean(extent[:2])
    central_lat = num.mean(extent[2:])
    ax = plt.axes(projection=ccrs.PlateCarree())
    ax.set_extent(extent)

    if topo is True:
        ax = add_topo(ax)
    ls_dark[ls_dark == 0] = num.nan
    ls_clear[ls_clear == 0] = num.nan
    scale_bar(ax, (0.1, 0.1), 5_0)
    ax.imshow(num.rot90(ls_dark.T),
              origin='upper',
              extent=extent,
              transform=ccrs.PlateCarree(),
              cmap='jet')
    ax.imshow(num.rot90(ls_clear.T),
              origin='upper',
              extent=extent,
              transform=ccrs.PlateCarree())

    ax.gridlines(draw_labels=True)

    addArrow(ax, scene)
    fig = plt.gcf()
    fig.set_size_inches((11, 11), forward=False)
    plt.savefig(fname + 'mask.svg', format='svg', dpi=300)
    plt.close()

    extent = [
        num.min(eastings),
        num.max(eastings),
        num.min(northings),
        num.max(northings)
    ]
    central_lon = num.mean(extent[:2])
    central_lat = num.mean(extent[2:])

    f, ax = plt.subplots(1, 1, subplot_kw=dict(projection=ccrs.PlateCarree()))
    ax.set_extent(extent)

    if topo is True:
        ax = add_topo(ax)
    ls_dark[ls_dark == 0] = num.nan
    ls_clear[ls_clear == 0] = num.nan
    scale_bar(ax, (0.1, 0.1), 5_0)
    ls_clear = grad.copy()
    ls_clear[ls_clear == 0] = num.nan

    h = ax.imshow(num.rot90(ls_clear.T),
                  origin='upper',
                  extent=extent,
                  transform=ccrs.PlateCarree(),
                  cmap="bone_r")

    gl = ax.gridlines(draw_labels=True)
    gl.ylabels_right = False
    gl.xlabels_top = False
    addArrow(ax, scene)
    divider = make_axes_locatable(ax)
    cax = divider.new_horizontal(size="5%", pad=0.1, axes_class=plt.Axes)
    f.add_axes(cax)
    plt.colorbar(h, cax=cax)
    fig = plt.gcf()
    fig.set_size_inches((11, 11), forward=False)
    plt.savefig(fname + 'grad.svg', format='svg', dpi=300)
    plt.close()

    eastings = longs
    northings = lats
    fig = plt.figure()

    extent = [
        num.min(eastings),
        num.max(eastings),
        num.min(northings),
        num.max(northings)
    ]
    central_lon = num.mean(extent[:2])
    central_lat = num.mean(extent[2:])
    ax = plt.axes(projection=ccrs.PlateCarree())
    ax.set_extent(extent)

    if topo is True:
        ax = add_topo(ax)
    ls_clear = grad_mask.copy()
    ls_clear[ls_clear < num.max(ls_clear) * 0.0000001] = num.nan

    ax.imshow(num.rot90(ls_clear.T),
              origin='upper',
              extent=extent,
              transform=ccrs.PlateCarree(),
              cmap="hot")
    h = ax.imshow(num.rot90(plt_img.T),
                  origin='upper',
                  extent=extent,
                  transform=ccrs.PlateCarree(),
                  cmap="seismic",
                  alpha=0.4)

    scale_bar(ax, (0.1, 0.1), 5_0)
    ax.gridlines(draw_labels=True)
    addArrow(ax, scene)
    fig = plt.gcf()
    fig.set_size_inches((11, 11), forward=False)
    plt.savefig(fname + 'mask_grad.svg', format='svg', dpi=300)
    plt.close()

    eastings = longs
    northings = lats
    fig = plt.figure()
    extent = [
        num.min(eastings),
        num.max(eastings),
        num.min(northings),
        num.max(northings)
    ]
    central_lon = num.mean(extent[:2])
    central_lat = num.mean(extent[2:])
    f, ax = plt.subplots(1, 1, subplot_kw=dict(projection=ccrs.PlateCarree()))
    ax.set_extent(extent)

    if topo is True:
        ax = add_topo(ax)

    ls_clear = coh_filt.copy()

    h = ax.imshow(num.rot90(ls_clear.T),
                  origin='upper',
                  extent=extent,
                  transform=ccrs.PlateCarree(),
                  cmap='seismic')

    scale_bar(ax, (0.1, 0.1), 5_0)
    gl = ax.gridlines(draw_labels=True)
    gl.ylabels_right = False
    gl.xlabels_top = False
    addArrow(ax, scene)
    divider = make_axes_locatable(ax)
    cax = divider.new_horizontal(size="5%", pad=0.1, axes_class=plt.Axes)
    f.add_axes(cax)
    plt.colorbar(h, cax=cax)

    fig = plt.gcf()
    fig.set_size_inches((11, 11), forward=False)
    plt.savefig(fname + 'filt.svg', format='svg', dpi=300)
    plt.close()

    eastings = longs
    northings = lats
    fig = plt.figure()
    extent = [
        num.min(eastings),
        num.max(eastings),
        num.min(northings),
        num.max(northings)
    ]
    central_lon = num.mean(extent[:2])
    central_lat = num.mean(extent[2:])
    f, ax = plt.subplots(1, 1, subplot_kw=dict(projection=ccrs.PlateCarree()))
    ax.set_extent(extent)

    if topo is True:
        ax = add_topo(ax)
    ls_clear = image.copy()
    ls_clear = ls_clear / num.sqrt(num.sum(ls_clear**2))
    ls_clear[ls_clear < num.max(ls_clear) * 0.01] = num.nan

    ax.imshow(num.rot90(ls_clear.T),
              origin='upper',
              extent=extent,
              transform=ccrs.PlateCarree(),
              cmap='hot')
    scale_bar(ax, (0.1, 0.1), 5_0)
    gl = ax.gridlines(draw_labels=True)
    gl.ylabels_right = False
    gl.xlabels_top = False
    addArrow(ax, scene)
    divider = make_axes_locatable(ax)
    cax = divider.new_horizontal(size="5%", pad=0.1, axes_class=plt.Axes)
    f.add_axes(cax)
    plt.colorbar(h, cax=cax)

    fig = plt.gcf()
    fig.set_size_inches((11, 11), forward=False)
    plt.savefig(fname + 'dir-comb.svg', format='svg', dpi=300)
    plt.close()

    def add_topo(ax):
        # shade function when the data is retrieved.
        shaded_srtm = PostprocessedRasterSource(SRTM1Source(), shade)
        # Add the shaded SRTM source to our map with a grayscale colormap.
        ax.add_raster(shaded_srtm, cmap='Greys')
        ax.add_feature(cartopy.feature.OCEAN)
        ax.add_feature(cartopy.feature.LAND, edgecolor='black')
        ax.add_feature(cartopy.feature.LAKES, edgecolor='black')
        ax.add_feature(cartopy.feature.RIVERS)
        return ax