Reads file, subtracts background. Returns [compensated image, background].
336640
def bg_compensate(img, sigma, splinepoints, scale):
    ''''''
    
    from PIL import Image
    import pylab
    from matplotlib.image import pil_to_array
    from centrosome.filter import canny
    import matplotlib

    img = Image.open(img)
    if img.mode=='I;16':
        # 16-bit image
        # deal with the endianness explicitly... I'm not sure
        # why PIL doesn't get this right.
        imgdata = np.fromstring(img.tostring(),np.uint8)
        imgdata.shape=(int(imgdata.shape[0]/2),2)
        imgdata = imgdata.astype(np.uint16)
        hi,lo = (0,1) if img.tag.prefix == 'MM' else (1,0)
        imgdata = imgdata[:,hi]*256 + imgdata[:,lo]
        img_size = list(img.size)
        img_size.reverse()
        new_img = imgdata.reshape(img_size)
        # The magic # for maximum sample value is 281
        if 281 in img.tag:
            img = new_img.astype(np.float32) / img.tag[281][0]
        elif np.max(new_img) < 4096:
            img = new_img.astype(np.float32) / 4095.
        else:
            img = new_img.astype(np.float32) / 65535.
    else:
        img = pil_to_array(img)
    
    pylab.subplot(1,3,1).imshow(img, cmap=matplotlib.cm.Greys_r)
    pylab.show()
    
    if len(img.shape)>2:
        raise ValueError('Image must be grayscale')

## Create mask that will fix problem when image has black areas outside of well
    edges = canny(img, np.ones(img.shape, bool), 2, .1, .3)
    ci = np.cumsum(edges, 0)
    cj = np.cumsum(edges, 1)
    i,j = np.mgrid[0:img.shape[0], 0:img.shape[1]]
    mask = ci > 0
    mask = mask & (cj > 0)
    mask[1:,:] &= (ci[0:-1,:] < ci[-1,j[0:-1,:]])
    mask[:,1:] &= (cj[:,0:-1] < cj[i[:,0:-1],-1])
    
    import time
    t0 = time.clock()
    bg = backgr(img, mask, MODE_AUTO, sigma, splinepoints=splinepoints, scale=scale)
    print("Executed in %f sec" % (time.clock() - t0))
    bg[~mask] = img[~mask]

    pylab.subplot(1,3,2).imshow(img - bg, cmap=matplotlib.cm.Greys_r)
    pylab.subplot(1,3,3).imshow(bg, cmap=matplotlib.cm.Greys_r)
    pylab.show()
1029597
def read(self, size=None):
        
        if size is None:
            size = self.size - self.position
        else:
            size = min(size, self.size - self.position)

        buf = b""
        while size > 0:
            while True:
                data, start, stop, offset = self.map[self.map_index]
                if start <= self.position < stop:
                    break
                else:
                    self.map_index += 1
                    if self.map_index == len(self.map):
                        self.map_index = 0
            length = min(size, stop - self.position)
            if data:
                self.fileobj.seek(offset + (self.position - start))
                buf += self.fileobj.read(length)
            else:
                buf += NUL * length
            size -= length
            self.position += length
        return buf
763070
def background(im, size, background=None, **kwargs):
    
    if not background:
        # Primary option not given, nothing to do.
        return im
    if not size[0] or not size[1]:
        # One of the dimensions aren't specified, can't do anything.
        return im
    x, y = im.size
    if x >= size[0] and y >= size[1]:
        # The image is already equal to (or larger than) the expected size, so
        # there's nothing to do.
        return im
    im = colorspace(im, replace_alpha=background, **kwargs)
    new_im = Image.new('RGB', size, background)
    if new_im.mode != im.mode:
        new_im = new_im.convert(im.mode)
    offset = (size[0]-x)//2, (size[1]-y)//2
    new_im.paste(im, offset)
    return new_im
861834
def _remove_white_background(image):
    """"""
    from PIL import ImageMath, Image
    if image.mode == "RGBA":
        bands = image.split()
        a = bands[3]
        rgb = [
            ImageMath.eval(
                'convert('
                'float(x + a - 255) * 255.0 / float(max(a, 1)) * '
                'float(min(a, 1)) + float(x) * float(1 - min(a, 1))'
                ', "L")',
                x=x, a=a
            )
            for x in bands[:3]
        ]
        return Image.merge(bands=rgb + [a], mode="RGBA")

    return image
983064
def read_relative_file(filename):
    """"""
    with open(join(dirname(abspath(__file__)), filename)) as f:
        return f.read()
998497
def read_roi(fileobj):
    '''
    
    '''
    # This is based on:
    # http://rsbweb.nih.gov/ij/developer/source/ij/io/RoiDecoder.java.html
    # http://rsbweb.nih.gov/ij/developer/source/ij/io/RoiEncoder.java.html

    SPLINE_FIT = 1
    DOUBLE_HEADED = 2
    OUTLINE = 4
    OVERLAY_LABELS = 8
    OVERLAY_NAMES = 16
    OVERLAY_BACKGROUNDS = 32
    OVERLAY_BOLD = 64
    SUB_PIXEL_RESOLUTION = 128
    DRAW_OFFSET = 256

    class RoiType:
        POLYGON = 0
        RECT = 1
        OVAL = 2
        LINE = 3
        FREELINE = 4
        POLYLINE = 5
        NOROI = 6
        FREEHAND = 7
        TRACED = 8
        ANGLE = 9
        POINT = 10

    def get8():
        s = fileobj.read(1)
        if not s:
            raise IOError('readroi: Unexpected EOF')
        return ord(s)

    def get16():
        b0 = get8()
        b1 = get8()
        return (b0 << 8) | b1

    def get32():
        s0 = get16()
        s1 = get16()
        return (s0 << 16) | s1

    def getfloat():
        v = np.int32(get32())
        return v.view(np.float32)

    #===========================================================================
    #Read Header data
    
    magic = fileobj.read(4)
    if magic != b'Iout':
        raise ValueError('Magic number not found')
        
    version = get16()

    # It seems that the roi type field occupies 2 Bytes, but only one is used
    roi_type = get8()
    # Discard second Byte:
    get8()
    
    top = get16()
    left = get16()
    bottom = get16()
    right = get16()
    n_coordinates = get16()
    x1 = getfloat()
    y1 = getfloat()
    x2 = getfloat()
    y2 = getfloat()
    stroke_width = get16()
    shape_roi_size = get32()
    stroke_color = get32()
    fill_color = get32()
    subtype = get16()
    
    options = get16()
    arrow_style = get8()
    arrow_head_size = get8()
    rect_arc_size = get16()
    position = get32()
    header2offset = get32()

    # End Header data
    #===========================================================================

    #RoiDecoder.java checks the version when setting sub-pixel resolution, therefore so do we
    subPixelResolution = ((options&SUB_PIXEL_RESOLUTION)!=0) and (version>=222)
    
    # Check exceptions
    if roi_type not in [RoiType.FREEHAND, RoiType.TRACED, RoiType.POLYGON, RoiType.RECT, RoiType.POINT]:
        raise NotImplementedError('roireader: ROI type %s not supported' % roi_type)
        
    if subtype != 0:
        raise NotImplementedError('roireader: ROI subtype %s not supported (!= 0)' % subtype)
    
    if roi_type == RoiType.RECT:
        if subPixelResolution:
            return np.array(
                [[y1, x1], [y1, x1+x2], [y1+y2, x1+x2], [y1+y2, x1]],
                dtype=np.float32)
        else:
            return np.array(
                [[top, left], [top, right], [bottom, right], [bottom, left]],
                dtype=np.int16)

    if subPixelResolution:
        getc = getfloat
        points = np.empty((n_coordinates, 2), dtype=np.float32)
        fileobj.seek(4*n_coordinates, 1)
    else:
        getc = get16
        points = np.empty((n_coordinates, 2), dtype=np.int16)

    points[:, 1] = [getc() for i in range(n_coordinates)]
    points[:, 0] = [getc() for i in range(n_coordinates)]

    if not subPixelResolution:
        points[:, 1] += left
        points[:, 0] += top

    return points
550683
def _get_background_color(self):
        """"""

        color = self.cell_attributes[self.key]["bgcolor"]
        return tuple(c / 255.0 for c in color_pack2rgb(color))
655557
def get_image_ratio(self, image):
        
        x, y = self.get_image_size(image)
        return float(x) / y
447737
function(sliceCode,data){
    	console.log(_outSpritePath);
        var _slice;
        for(var key in sliceCode){
            _slice = sliceCode[key];
            var _code = "background-image: url(.";
                _code += _outSpritePath.slice(_outSpritePath.lastIndexOf("/"),_outSpritePath.length);
                _code += "/";
                _code += _outSpriteName;
                _code += ");";
                _code += "background-position: -";
                _code += _slice.x;
                _code += "px -";
                _code += _slice.y;
                _code += "px;";
            data = data.replace(_slice.code,_code);
        }
        return data;
    }
1043358
def _read(self):
        
        if self._dask:
            d = da.from_delayed(
                delayed(read_from_bpch, )(
                    self.filename, self.file_position, self.shape,
                    self.dtype, self.endian, use_mmap=self._mmap
                ),
                self.shape, self.dtype
            )
        else:
            d = read_from_bpch(
                    self.filename, self.file_position, self.shape,
                    self.dtype, self.endian, use_mmap=self._mmap
            )

        return d
1322147
def iterstraight(self, raw):
        

        # length of row, in bytes
        rb = self.row_bytes
        a = array('B')
        # The previous (reconstructed) scanline.  None indicates first
        # line of image.
        recon = None
        for some in raw:
            a.extend(some)
            while len(a) >= rb + 1:
                filter_type = a[0]
                scanline = a[1:rb+1]
                del a[:rb+1]
                recon = self.undo_filter(filter_type, scanline, recon)
                yield recon
        if len(a) != 0:
            # :file:format We get here with a file format error:
            # when the available bytes (after decompressing) do not
            # pack into exact rows.
            raise FormatError(
              'Wrong size for decompressed IDAT chunk.')
        assert len(a) == 0
344441
function readPixel(png, x, y) {
  if(x < 0 || y <0 || x > png.width || y > png.height)
    return null;

  var idx = (png.width * y + x) << 2;
  var background = [png.data[idx], png.data[idx+1], png.data[idx+2], png.data[idx+3]];
  return background;
}
171097
def load_average(self):
        
        with io.open(self.load_average_file, 'r') as f:
            file_columns = f.readline().strip().split()
            return float(file_columns[self._load_average_file_column])
77079
def image_load_time(self):
        
        load_times = self.get_load_times('image')
        return round(mean(load_times), self.decimal_precision)
934980
def guess_lineno(file):
    
    offset = file.tell()
    file.seek(0)
    startpos = 0
    lineno = 1
    # looks like file.read() return bytes in python3
    # so I need more complicated algorithm here
    while True:
        line = file.readline()
        if not line:
            break
        endpos = file.tell()
        if startpos <= offset < endpos:
            break
        lineno += 1
    file.seek(offset)
    return lineno
731361
function getIncludedContent(fileName, css) {
      return fs.readFileAsync(dirname + fileName, {encoding: 'utf8'}).then(function(data) {
        if (css && conf.cssUrlReplacer) {
          data = data.replace(cssurl, function(matched, pref, theUrl, suf) {
            //console.log('readFileAsync, css replacer: ' + url + ', ' + theUrl);
            return pref + conf.cssUrlReplacer(theUrl) + suf;
          });
        }
        incfiles[fileName] = data;
      })
      .catch(function(e) {
        // If we can't read the file, just issue a console warning and continue.
        // Content for this file will not be inlined.
        console.warn('Inliner:\n' + e);
      });
    }
393829
def readGif(filename, asNumpy=True):
    

    # Check PIL
    if PIL is None:
        raise RuntimeError("Need PIL to read animated gif files.")

    # Check Numpy
    if np is None:
        raise RuntimeError("Need Numpy to read animated gif files.")

    # Check whether it exists
    if not os.path.isfile(filename):
        raise IOError('File not found: ' + str(filename))

    # Load file using PIL
    pilIm = PIL.Image.open(filename)
    pilIm.seek(0)

    # Read all images inside
    images = []
    try:
        while True:
            # Get image as numpy array
            tmp = pilIm.convert()  # Make without palette
            a = np.asarray(tmp)
            if len(a.shape) == 0:
                raise MemoryError("Too little memory to convert PIL image to array")
            # Store, and next
            images.append(a)
            pilIm.seek(pilIm.tell() + 1)
    except EOFError:
        pass

    # Convert to normal PIL images if needed
    if not asNumpy:
        images2 = images
        images = []
        for im in images2:
            images.append(PIL.Image.fromarray(im))

    # Done
    return images