Read a header from a MarResearch .image file.
960295
def readmarheader(filename):
    """"""
    with open(filename, 'rb') as f:
        intheader = np.fromstring(f.read(10 * 4), np.int32)
        floatheader = np.fromstring(f.read(15 * 4), '<f4')
        strheader = f.read(24)
        f.read(4)
        otherstrings = [f.read(16) for i in range(29)]
    return {'Xsize': intheader[0], 'Ysize': intheader[1], 'MeasTime': intheader[8],
            'BeamPosX': floatheader[7], 'BeamPosY': floatheader[8],
            'Wavelength': floatheader[9], 'Dist': floatheader[10],
            '__Origin__': 'MarResearch .image', 'recordlength': intheader[2],
            'highintensitypixels': intheader[4],
            'highintensityrecords': intheader[5],
            'Date': dateutil.parser.parse(strheader),
            'Detector': 'MARCCD', '__particle__': 'photon'}
919142
def read_header(self):
        """"""
        format = '!HHHHHH'
        length = struct.calcsize(format)
        info = struct.unpack(format,
                self.data[self.offset:self.offset + length])
        self.offset += length

        self.id = info[0]
        self.flags = info[1]
        self.num_questions = info[2]
        self.num_answers = info[3]
        self.num_authorities = info[4]
        self.num_additionals = info[5]
255405
def _write_header(self, image, hdu):
        """"""
        hduhdr = hdu.header

        # Ginga image header object for the given extension only.
        # Cannot use get_header() because that might also return PRI hdr.
        ghdr = image.metadata['header']

        for key in ghdr:
            # Need this to avoid duplication because COMMENT is a weird field
            if key.upper() == 'COMMENT':
                continue

            bnch = ghdr.get_card(key)

            # Insert new keyword
            if key not in hduhdr:
                hduhdr[key] = (bnch.value, bnch.comment)

            # Update existing keyword
            elif hduhdr[key] != bnch.value:
                hduhdr[key] = bnch.value
483877
def _parseImageNtHeaders(self, data, imageDosHeader):
        """"""
        inth = self._classes.IMAGE_NT_HEADERS.from_buffer(data, imageDosHeader.header.e_lfanew)

        if inth.Signature != b'PE':
            raise BinaryError('No valid PE/COFF file')

        return ImageNtHeaderData(header=inth)
413519
@Override
    public ImageHeader readHeader(InputStream input) throws IOException
    {
        checkSkippedError(input.skip(2), 2);
        int current = input.read();
        while (255 == current)
        {
            final int marker = input.read();
            final int len = readInt(input, 2, true);
            if (MARKER_1 == marker || MARKER_2 == marker || MARKER_3 == marker)
            {
                final long skipped = input.skip(1);
                checkSkippedError(skipped, 1);
                final int height = readInt(input, 2, true);
                final int width = readInt(input, 2, true);
                final ImageFormat format = ImageFormat.JPG;

                return new ImageHeaderModel(width, height, format);
            }
            final long skipped = input.skip(len - 2L);
            checkSkippedError(skipped, len - 2);
            current = input.read();
        }
        throw new IOException(ERROR_JPG);
    }
896447
def read_chd_header(chd_file):
    

    with open(chd_file, "rb") as f:
        header = {
            "cinefileheader": cine.CINEFILEHEADER(),
            "bitmapinfoheader": cine.BITMAPINFOHEADER(),
            "setup": cine.SETUP(),
        }
        f.readinto(header["cinefileheader"])
        f.readinto(header["bitmapinfoheader"])
        f.readinto(header["setup"])

    return header
206176
@Override
    public ImageHeader readHeader(InputStream input) throws IOException
    {
        final long toSkip = 8L;
        final boolean bigEndian = 'M' == input.read();
        checkSkippedError(input.skip(HEADER_SIZE - 1L), HEADER_SIZE - 1);
        final int ifd = readInt(input, 4, bigEndian);
        input.skip(ifd - toSkip);
        // checkSkippedError(skipped, ifd - toSkip); fail when reading from JAR, not needed
        final int entries = readInt(input, 2, bigEndian);

        int width = -1;
        int height = -1;
        for (int i = 1; i <= entries; i++)
        {
            final int tag = readInt(input, 2, bigEndian);
            final int fieldType = readInt(input, 2, bigEndian);
            readInt(input, VAL_OFFSET_BYTES, bigEndian);
            final int valOffset;
            if (VAL_OFFSET_FIELD_1 == fieldType || VAL_OFFSET_FIELD_2 == fieldType)
            {
                valOffset = readInt(input, 2, bigEndian);
                final long skipped = input.skip(2);
                checkSkippedError(skipped, 2);
            }
            else
            {
                valOffset = readInt(input, VAL_OFFSET_BYTES, bigEndian);
            }
            if (TAG_WIDTH == tag)
            {
                width = valOffset;
            }
            else if (TAG_HEIGHT == tag)
            {
                height = valOffset;
            }
            if (-1 != width && -1 != height)
            {
                return new ImageHeaderModel(width, height, ImageFormat.TIFF);
            }
        }
        throw new IOException(ERROR_TIFF);
    }
1099688
def _parseImageDosHeader(self, data):
        """"""
        ioh = IMAGE_DOS_HEADER.from_buffer(data)
        if ioh.e_magic != b'MZ':
            raise BinaryError('No valid PE/COFF file')

        return ImageDosHeaderData(header=ioh)
394352
def parse_header(filename):
    '''
    '''
    with open(filename, 'rb') as fh:
        content = '\n'.join(fh.read().splitlines())

    content = sub('\t', ' ', content)
    content = strip_comments(content)

    # first get the functions
    content = split(func_pat_short, content)

    for i, s in enumerate(content):
        if i % 2 and content[i].strip():  # matched a prototype
            try:
                content[i] = parse_prototype(content[i])
            except Exception as e:
                traceback.print_exc()

    # now process structs
    res = []
    for i, item in enumerate(content):
        if not isinstance(item, str):  # if it's already a func etc. skip it
            res.append(item)
            continue

        items = split(struct_pat, item)
        j = 0
        while j < len(items):
            if not j % 5:
                res.append(items[j])
                j += 1
            else:
                if items[j].strip() == 'enum':
                    res.append(parse_enum(*items[j + 1: j + 4]))
                else:
                    res.append(parse_struct(*items[j + 1: j + 4]))
                j += 4

    # now do remaining simple typedefs
    content = res
    res = []
    for i, item in enumerate(content):
        if not isinstance(item, str):  # if it's already processed skip it
            res.append(item)
            continue

        items = split(typedef_pat, item)
        for j, item in enumerate(items):
            res.append(TypeDef(item.strip()) if j % 2 else item)

    content = [c for c in res if not isinstance(c, str) or c.strip()]
    return content
280175
def _read_header(self, header_str):
        """"""

        # regular expressions
        re_float = '[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?'
        re_uint = '\d+'
        re_binning = '{d} in (?P<nbins>' + re_uint + ') bin[ s] '
        re_binning += 'of (?P<binwidth>' + re_float + ') {unit}'

        # map of dimensions and units
        dim_units = {
            'X': 'cm',
            'Y': 'cm',
            'Z': 'cm',
            'R': 'cm',
            'Phi': 'deg',
            'Theta': 'deg',
        }

        # retrieve binning info
        self.dimensions = []
        for line in header_str.splitlines():

            for dim, unit in dim_units.items():
                re_tmp = re_binning.format(d=dim, unit=unit)
                regex = re.compile(re_tmp)
                match = regex.search(line)

                if match:
                    N = int(match.group('nbins'))
                    width = float(match.group('binwidth'))
                    dimension = BinnedDimension(dim, unit, N, width)
                    self.dimensions.append(dimension)

        # retrieve scored quantity info
        re_score_unit = '# (?P<quant>.+) \( (?P<unit>.+) \) : (?P<stats>.+)'
        re_score_unitless = '# (?P<quant>.+) : (?P<stats>.+)'
        regex_unit = re.compile(re_score_unit)
        regex_unitless = re.compile(re_score_unitless)

        for line in header_str.splitlines():

            match = regex_unit.search(line)
            if match:
                self.quantity = match.group('quant')
                self.unit = match.group('unit')
                self.statistics = match.group('stats').split()
                break

            match = regex_unitless.search(line)
            if match:
                self.quantity = match.group('quant')
                self.unit = None
                self.statistics = match.group('stats').split()
                break
726826
def ReadTif(tifFile):
        """"""
        img = Image.open(tifFile)
        img = np.array(img)
        return img
1158036
def check_image_file_header(filename):
  """"""
  with tf.gfile.Open(filename, 'rb') as f:
    magic = read32(f)
    read32(f)  # num_images, unused
    rows = read32(f)
    cols = read32(f)
    if magic != 2051:
      raise ValueError('Invalid magic number %d in MNIST file %s' % (magic,
                                                                     f.name))
    if rows != 28 or cols != 28:
      raise ValueError(
          'Invalid MNIST file %s: Expected 28x28 images, found %dx%d' %
          (f.name, rows, cols))
1328353
def loadImageData(filename, spacing=()):
    """"""
    if not os.path.isfile(filename):
        colors.printc("~noentry File not found:", filename, c=1)
        return None

    if ".tif" in filename.lower():
        reader = vtk.vtkTIFFReader()
    elif ".slc" in filename.lower():
        reader = vtk.vtkSLCReader()
        if not reader.CanReadFile(filename):
            colors.printc("~prohibited Sorry bad slc file " + filename, c=1)
            exit(1)
    elif ".vti" in filename.lower():
        reader = vtk.vtkXMLImageDataReader()
    elif ".mhd" in filename.lower():
        reader = vtk.vtkMetaImageReader()
    reader.SetFileName(filename)
    reader.Update()
    image = reader.GetOutput()
    if len(spacing) == 3:
        image.SetSpacing(spacing[0], spacing[1], spacing[2])
    return image
1006190
def read(self, source_path):
        """"""

        with pelican_open(source_path) as text:
            parts = text.split('----', 1)
            if len(parts) == 2:
                headerlines = parts[0].splitlines()
                headerpairs = map(lambda l: l.split(':', 1), headerlines)
                headerdict = {pair[0]: pair[1].strip()
                              for pair in headerpairs
                              if len(pair) == 2}
                metadata = self._parse_metadata(headerdict)
                content = textile(parts[1])
            else:
                metadata = {}
                content = textile(text)

        return content, metadata
312040
def _read_file_header(self):
        """"""
        header = self.fileobj.readline()
        payload1 = self.fileobj.readline()
        payload2 = self.fileobj.readline()
        version, reserved, organisation = payload1.split(None, 2)
        self.fileobj.readline() # Lose the separator newline
        self.header_read = True
        # print "--------------------------------------------------"
        # print header,"\n", payload1, "\n", payload2,"\n"
        # print "--------------------------------------------------"
        if self.version and int(self.version) != version:
            raise IOError("Version mismatch. Requested version was '%s' but version in file was '%s'"%(self.version, version))
        
        if version == '1':
            url, ip_address, date, content_type, length = header.split()
            self.file_headers = {"ip_address" : ip_address,
                                 "date" : datetime.datetime.strptime(date, "%Y%m%d%H%M%S"),
                                 "org" : organisation}
            self.version = 1
        elif version == '2':
            url, ip_address, date, content_type, result_code, checksum, location, offset, filename, length  = header.split()
            self.file_headers = {"ip_address" : ip_address,
                                 "date" : datetime.datetime.strptime(date, "%Y%m%d%H%M%S"),
                                 "org" : organisation}
            self.version = 2
        else:
            raise IOError("Unknown ARC version '%s'"%version)
47380
def parse_header(options = {})
      check_header
      @hdr = parse_basic_header
      @extended_header = parse_extended_header

      # Optional image gathering
      read_image if options[:image]
      get_image_narray(@image_rubyarray, @hdr['dim']) if options[:narray]

      @success = true
    end
1292328
def readmar(filename):
    
    hed = header.readmarheader(filename)
    with open(filename, 'rb') as f:
        h = f.read(hed['recordlength'])
        data = np.fromstring(
            f.read(2 * hed['Xsize'] * hed['Ysize']), '<u2').astype(np.float64)
        if hed['highintensitypixels'] > 0:
            raise NotImplementedError(
                'Intensities over 65535 are not yet supported!')
        data = data.reshape(hed['Xsize'], hed['Ysize'])
    return data, hed