Display unrectified image with spectrails and frontiers.

        Parameters
        ----------
        slitlet2d : numpy array
            Array containing the unrectified slitlet image.
550795
def ximshow_unrectified(self, slitlet2d):
        

        title = "Slitlet#" + str(self.islitlet)
        ax = ximshow(slitlet2d, title=title,
                     first_pixel=(self.bb_nc1_orig, self.bb_ns1_orig),
                     show=False)
        xdum = np.linspace(1, EMIR_NAXIS1, num=EMIR_NAXIS1)
        ylower = self.list_spectrails[0](xdum)
        ax.plot(xdum, ylower, 'b-')
        ymiddle = self.list_spectrails[1](xdum)
        ax.plot(xdum, ymiddle, 'b--')
        yupper = self.list_spectrails[2](xdum)
        ax.plot(xdum, yupper, 'b-')
        ylower_frontier = self.list_frontiers[0](xdum)
        ax.plot(xdum, ylower_frontier, 'b:')
        yupper_frontier = self.list_frontiers[1](xdum)
        ax.plot(xdum, yupper_frontier, 'b:')
        pause_debugplot(debugplot=self.debugplot, pltshow=True)
726826
def ReadTif(tifFile):
        """"""
        img = Image.open(tifFile)
        img = np.array(img)
        return img
508764
def gmdaArray(arry, dtype, mask=None, numGhosts=1):
    
    a = numpy.array(arry, dtype)
    res = GhostedMaskedDistArray(a.shape, a.dtype)
    res.mask = mask
    res.setNumberOfGhosts(numGhosts)
    res[:] = a
    return res
1251747
def undistortWCS(refwcs):
    
    wcslin = stwcs.distortion.utils.output_wcs([refwcs])

    outwcs = stwcs.wcsutil.HSTWCS()
    outwcs.wcs = wcslin.wcs
    outwcs.wcs.set()
    outwcs.setPscale()
    outwcs.setOrient()
    outwcs.sip = None

    # Update instrument specific keywords
    outwcs.inst_kw = refwcs.inst_kw
    for kw in refwcs.inst_kw:
        outwcs.__dict__[kw] = refwcs.__dict__[kw]
    outwcs.pixel_shape = wcslin.pixel_shape

    return outwcs
231545
def blit_np_array(self, array):
    """"""
    with sw("make_surface"):
      raw_surface = pygame.surfarray.make_surface(array.transpose([1, 0, 2]))
    with sw("draw"):
      pygame.transform.scale(raw_surface, self.surf.get_size(), self.surf)
320114
def mask_roi_digi(self):
        
        # http://stackoverflow.com/q/24205045/#24206440
        A = np.vstack([self.mask_1.mask_roi_sparse,self.mask_2.mask_roi_sparse]).T
        B = self.mask_roi_unique

        AA = np.ascontiguousarray(A)
        BB = np.ascontiguousarray(B)
         
        dt = np.dtype((np.void, AA.dtype.itemsize * AA.shape[1]))
        a = AA.view(dt).ravel()
        b = BB.view(dt).ravel()
         
        idx = np.argsort(b)
        indices = np.searchsorted(b[idx],a)
        return idx[indices]
1316539
def convert_to_odl(image):
    """"""

    shape = image.shape

    if len(shape) == 2:
        space = odl.uniform_discr([0, 0], shape, shape)
    elif len(shape) == 3:
        d = shape[2]
        shape = shape[:2]
        image = np.transpose(image, (2, 0, 1))
        space = odl.uniform_discr([0, 0], shape, shape) ** d

    image = space.element(image)

    return image
842476
private RectF getDisplayRect(Matrix matrix) {
        ImageView imageView = getImageView();

        if (null != imageView) {
            Drawable d = imageView.getDrawable();
            if (null != d) {
                mDisplayRect.set(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
                matrix.mapRect(mDisplayRect);
                return mDisplayRect;
            }
        }
        return null;
    }
1178460
def image2array(self, image):
        
        idex_mask = self._idex_mask
        array = util.image2array(image)
        if self._idex_mask_bool is True:
            return array[idex_mask == 1]
        else:
            return array
165763
def _coarsenImage(image, f):
    '''
    
    '''
    from skimage.morphology import square
    from skimage.filters import rank
    from skimage.transform._warps import rescale
    selem = square(f)
    arri = rank.mean(image, selem=selem)
    return rescale(arri, 1 / f, order=0)
519200
def undistortPoints(self, points, keepSize=False):
        '''
        
        '''
        s = self.img.shape
        cam = self.coeffs['cameraMatrix']
        d = self.coeffs['distortionCoeffs']

        pts = np.asarray(points, dtype=np.float32)
        if pts.ndim == 2:
            pts = np.expand_dims(pts, axis=0)

        (newCameraMatrix, roi) = cv2.getOptimalNewCameraMatrix(cam,
                                                               d, s[::-1], 1,
                                                               s[::-1])
        if not keepSize:
            xx, yy = roi[:2]
            pts[0, 0] -= xx
            pts[0, 1] -= yy

        return cv2.undistortPoints(pts,
                                   cam, d, P=newCameraMatrix)
943980
def getdarkimg(self,chip):
        
        sci_chip = self._image[self.scienceExt,chip]
        return np.ones(sci_chip.image_shape,dtype=sci_chip.image_dtype)*sci_chip.darkcurrent
57952
def _array2image_list(self, array):
        
        image_list = []
        k = 0
        for i in range(self._num_bands):
            if self._compute_bool[i] is True:
                num_data = self.num_response_list[i]
                array_i = array[k:k + num_data]
                image_i = self._imageModel_list[i].ImageNumerics.array2image(array_i)
                image_list.append(image_i)
                k += num_data
        return image_list
1182554
def show_slice(data2d, contour2d=None, seeds2d=None):
    

    import copy as cp
    # Show results

    colormap = cp.copy(plt.cm.get_cmap('brg'))
    colormap._init()
    colormap._lut[:1:, 3] = 0

    plt.imshow(data2d, cmap='gray', interpolation='none')
    if contour2d is not None:
        plt.contour(contour2d, levels=[0.5, 1.5, 2.5])
    if seeds2d is not None:
        # Show results
        colormap = copy.copy(plt.cm.get_cmap('Paired'))
        # colormap = copy.copy(plt.cm.get_cmap('gist_rainbow'))
        colormap._init()

        colormap._lut[0, 3] = 0

        tmp0 = copy.copy(colormap._lut[:,0])
        tmp1 = copy.copy(colormap._lut[:,1])
        tmp2 = copy.copy(colormap._lut[:,2])

        colormap._lut[:, 0] = sigmoid(tmp0, 0.5, 5)
        colormap._lut[:, 1] = sigmoid(tmp1, 0.5, 5)
        colormap._lut[:, 2] = 0# sigmoid(tmp2, 0.5, 5)
        # seed 4
        colormap._lut[140:220:, 1] = 0.7# sigmoid(tmp2, 0.5, 5)
        colormap._lut[140:220:, 0] = 0.2# sigmoid(tmp2, 0.5, 5)
        # seed 2
        colormap._lut[40:120:, 1] = 1.# sigmoid(tmp2, 0.5, 5)
        colormap._lut[40:120:, 0] = 0.1# sigmoid(tmp2, 0.5, 5)


        # seed 2
        colormap._lut[120:150:, 0] = 1.# sigmoid(tmp2, 0.5, 5)
        colormap._lut[120:150:, 1] = 0.1# sigmoid(tmp2, 0.5, 5)

        # my colors

        # colormap._lut[1,:] = [.0,.1,.0,1]
        # colormap._lut[2,:] = [.1,.1,.0,1]
        # colormap._lut[3,:] = [.1,.1,.1,1]
        # colormap._lut[4,:] = [.3,.3,.3,1]

        plt.imshow(seeds2d, cmap=colormap, interpolation='none')
1210025
def slices(img, shape=[3, 4]):
    
    sh = np.asarray(shape)
    i_max = np.prod(sh)
    allimg = np.zeros(img.shape[-2:] * sh)

    for i in range(0, i_max):
        # i = 0
        islice = round((img.shape[0] / float(i_max)) * i)
        #         print(islice)
        imgi = img[islice, :, :]
        coords = index_to_coords(i, sh)
        aic = np.asarray(img.shape[-2:]) * coords

        allimg[aic[0]:aic[0] + imgi.shape[-2], aic[1]:aic[1] + imgi.shape[-1]] = imgi

    #     plt.imshow(imgi)
    #     print(imgi.shape)
    #     print(img.shape)
    return allimg
1228793
def _sigmaclip_noaxis(self, data, masked=True, return_bounds=False,
                          copy=True):
        

        filtered_data = data.ravel()

        # remove masked values and convert to ndarray
        if isinstance(filtered_data, np.ma.MaskedArray):
            filtered_data = filtered_data.data[~filtered_data.mask]

        # remove invalid values
        good_mask = np.isfinite(filtered_data)
        if np.any(~good_mask):
            filtered_data = filtered_data[good_mask]
            warnings.warn('Input data contains invalid values (NaNs or '
                          'infs), which were automatically clipped.',
                          AstropyUserWarning)

        nchanged = 1
        iteration = 0
        while nchanged != 0 and (iteration < self.maxiters):
            iteration += 1
            size = filtered_data.size
            self._compute_bounds(filtered_data, axis=None)
            filtered_data = filtered_data[(filtered_data >= self._min_value) &
                                          (filtered_data <= self._max_value)]
            nchanged = size - filtered_data.size

        self._niterations = iteration

        if masked:
            # return a masked array and optional bounds
            filtered_data = np.ma.masked_invalid(data, copy=copy)

            # update the mask in place, ignoring RuntimeWarnings for
            # comparisons with NaN data values
            with np.errstate(invalid='ignore'):
                filtered_data.mask |= np.logical_or(data < self._min_value,
                                                    data > self._max_value)

        if return_bounds:
            return filtered_data, self._min_value, self._max_value
        else:
            return filtered_data
466425
def _get_data_to_display(self, eopatch):
        
        feature_type, feature_name = next(self.feature(eopatch))

        image_seq = eopatch[feature_type][feature_name]
        single_channel = False
        if image_seq.ndim == 3:
            # single channel
            single_channel = True
        elif image_seq.ndim == 4:
            # If multi-channel make sure indexing is correct
            n_channels = image_seq.shape[-1]
            if n_channels == 1:
                image_seq = np.squeeze(image_seq, axis=-1)
                single_channel = True
            elif n_channels == 3:
                pass
            else:
                if (self.indices is not None) and ((len(self.indices) == 1) or (len(self.indices) == 3)):
                    image_seq = image_seq[..., self.indices]
                    if len(self.indices) == 1:
                        image_seq = np.squeeze(image_seq, axis=-1)
                        single_channel = True
                else:
                    raise ValueError("Specify valid indices for multi-channel EOPatch")
        else:
            raise ValueError("Unsupported format for EOPatch")
        return image_seq, single_channel