Python png 模块,Reader() 实例源码

我们从Python开源项目中,提取了以下25个代码示例,用于说明如何使用png.Reader()

项目:flownet2-tf    作者:sampepose    | 项目源码 | 文件源码
def read_flow_png(flow_file):
    """
    Read optical flow from KITTI .png file
    :param flow_file: name of the flow file
    :return: optical flow data in matrix
    """
    flow_object = png.Reader(filename=flow_file)
    flow_direct = flow_object.asDirect()
    flow_data = list(flow_direct[2])
    (w, h) = flow_direct[3]['size']
    flow = np.zeros((h, w, 3), dtype=np.float64)
    for i in range(len(flow_data)):
        flow[i, :, 0] = flow_data[i][0::3]
        flow[i, :, 1] = flow_data[i][1::3]
        flow[i, :, 2] = flow_data[i][2::3]

    invalid_idx = (flow[:, :, 2] == 0)
    flow[:, :, 0:2] = (flow[:, :, 0:2] - 2 ** 15) / 64.0
    flow[invalid_idx, 0] = 0
    flow[invalid_idx, 1] = 0
    return flow
项目:flownet2-tf    作者:sampepose    | 项目源码 | 文件源码
def read_disp_png(file_name):
    """
    Read optical flow from KITTI .png file
    :param file_name: name of the flow file
    :return: optical flow data in matrix
    """
    image_object = png.Reader(filename=file_name)
    image_direct = image_object.asDirect()
    image_data = list(image_direct[2])
    (w, h) = image_direct[3]['size']
    channel = len(image_data[0]) / w
    flow = np.zeros((h, w, channel), dtype=np.uint16)
    for i in range(len(image_data)):
        for j in range(channel):
            flow[i, :, j] = image_data[i][j::channel]
    return flow[:, :, 0] / 256
项目:fondamentibook    作者:xelatihy    | 项目源码 | 文件源码
def load(filename):
    '''Carica l'immagine in formato PNG dal file filename, la converte nel
    formato a matrice di tuple e la ritorna'''
    with open(filename,'rb') as f:
        # legge l'immagine come RGB a 256 valori tramite l'oggetto Reader
        iw, ih, png_img, _ = png.Reader(file=f).asRGB8()
        # converte l'immagine in lista di liste di tuple
        img = []
        for png_row in png_img:
            row = []
            # l'immagine PNG ha i colori come un unico array
            # quindi li leggiamo tre alla volta e impacchettiamo in una tupla
            for i in range(0,len(png_row),3):
                row.append( (png_row[i+0],png_row[i+1],png_row[i+2]) )
            img.append( row )
    return img
项目:fondamentibook    作者:xelatihy    | 项目源码 | 文件源码
def load(filename):
    '''Carica l'immagine in formato PNG dal file 
    filename, la converte nel formato a matrice 
    di tuple e la ritorna'''
    with open(filename,'rb') as f:
        # legge l'immagine come RGB a 256 valori
        r = png.Reader(file=f)
        iw, ih, png_img, _ = r.asRGB8()
        # converte in lista di liste di tuple
        img = []
        for png_row in png_img:
            row = []
            # l'immagine PNG ha i colori in 
            # un'unico array quindi li leggiamo 
            # tre alla volta in una tupla
            for i in range(0,len(png_row),3):
                row.append( ( png_row[i+0], 
                              png_row[i+1],
                              png_row[i+2] ) )
            img.append( row )
    return img
项目:mrflow    作者:jswulff    | 项目源码 | 文件源码
def flow_read_png(fpath):
    """
    Read KITTI optical flow, returns u,v,valid mask

    """
    if not has_png:
        print('Error. Please install the PyPNG library')
        return

    R = png.Reader(fpath)
    width,height,data,_ = R.asDirect()
    I = np.array(map(lambda x:x,data)).reshape((height,width,3))
    u_ = I[:,:,0]
    v_ = I[:,:,1]
    valid = I[:,:,2]

    u = (u_.astype('float64')-2**15)/64.0
    v = (v_.astype('float64')-2**15)/64.0

    return u,v,valid
项目:bmii    作者:psurply    | 项目源码 | 文件源码
def load_sprite_from_png(self, filename, addr):
        logging.debug("VRAM: Loading %s at %x", filename, addr)
        reader = png.Reader(filename=filename)
        pic = reader.read()

        self.set_vram_cursor(addr)
        for line in pic[2]:
            i = 0
            word = 0
            for px in line:
                word |= px << i
                i += pic[3]['bitdepth']
                if i > 7:
                    self.write_vram(None, word)
                    i = 0
                    word = 0
项目:flownetS_tensorflow    作者:studian    | 项目源码 | 文件源码
def read_disp_png(disp_file):
    """
    Read kitti disp from .png file
    :param disp_file:
    :return:
    """
    image_object = png.Reader(filename=disp_file)
    image_direct = image_object.asDirect()
    image_data = list(image_direct[2])
    (w, h) = image_direct[3]['size']
    channel = len(image_data[0]) / w
    disp = np.zeros((h, w, channel), dtype=np.uint16)
    for i in range(len(image_data)):
        for j in range(channel):
            disp[i, :, j] = image_data[i][j::channel]
    return disp[:, :, 0] / 256

# TODO: function flow_write(flow_file)
项目:flownetS_tensorflow    作者:studian    | 项目源码 | 文件源码
def read_disp_png(file_name):
    """
    Read optical flow from KITTI .png file
    :param file_name: name of the flow file
    :return: optical flow data in matrix
    """
    image_object = png.Reader(filename=file_name)
    image_direct = image_object.asDirect()
    image_data = list(image_direct[2])
    (w, h) = image_direct[3]['size']
    channel = len(image_data[0]) / w
    flow = np.zeros((h, w, channel), dtype=np.uint16)
    for i in range(len(image_data)):
        for j in range(channel):
            flow[i, :, j] = image_data[i][j::channel]
    return flow[:, :, 0] / 256
项目:flownetS_tensorflow    作者:studian    | 项目源码 | 文件源码
def read_png_file(flow_file):
    """
    Read from KITTI .png file
    :param flow_file: name of the flow file
    :return: optical flow data in matrix
    """
    flow_object = png.Reader(filename=flow_file)
    flow_direct = flow_object.asDirect()
    flow_data = list(flow_direct[2])
    (w, h) = flow_direct[3]['size']
    print "Reading %d x %d flow file in .png format" % (h, w)
    flow = np.zeros((h, w, 3), dtype=np.float64)
    for i in range(len(flow_data)):
        flow[i, :, 0] = flow_data[i][0::3]
        flow[i, :, 1] = flow_data[i][1::3]
        flow[i, :, 2] = flow_data[i][2::3]

    invalid_idx = (flow[:, :, 2] == 0)
    flow[:, :, 0:2] = (flow[:, :, 0:2] - 2 ** 15) / 64.0
    flow[invalid_idx, 0] = 0
    flow[invalid_idx, 1] = 0
    return flow
项目:flownetS_tensorflow    作者:studian    | 项目源码 | 文件源码
def read_disp_png(disp_file):
        """
        Read kitti disp from .png file
        :param disp_file:
        :return:
        """
        image_object = png.Reader(filename=disp_file)
        image_direct = image_object.asDirect()
        image_data = list(image_direct[2])
        (w, h) = image_direct[3]['size']
        channel = len(image_data[0]) / w
        disp = np.zeros((h, w, channel), dtype=np.uint16)
        for i in range(len(image_data)):
            for j in range(channel):
                disp[i, :, j] = image_data[i][j::channel]
        return disp[:, :, 0] / 256
项目:openbadges-bakery    作者:concentricsky    | 项目源码 | 文件源码
def bake(imageFile, assertion_string, newfile=None):
    """
    Embeds a serialized representation of a badge instance in a PNG image file.
    """
    encoded_assertion_string = codecs.getwriter('utf-8')(assertion_string)
    reader = png.Reader(file=imageFile)

    if newfile is None:
        newfile = NamedTemporaryFile(suffix='.png')

    chunkheader = b'openbadges\x00\x00\x00\x00\x00'
    chunk_content = chunkheader + encoded_assertion_string.stream.encode('utf-8')
    badge_chunk = ('iTXt', chunk_content)
    png.write_chunks(newfile, baked_chunks(reader.chunks(), badge_chunk))

    newfile.seek(0)
    return newfile
项目:segno    作者:heuer    | 项目源码 | 文件源码
def _get_png_info(**kw):
    """\
    Returns the width, height and the pixels of the provided PNG file.
    """
    reader = PNGReader(**kw)
    w, h, pixels, meta = reader.asDirect()
    return w, h, _make_pixel_array(pixels, meta['greyscale'])
项目:properties    作者:aranzgeo    | 项目源码 | 文件源码
def validate(self, instance, value):
        """Checks if value is an open PNG file, valid filename, or png.Image

        Returns an open bytestream of the image
        """
        # Pass if already validated
        if getattr(value, '__valid__', False):
            return value
        # Validate that value is PNG
        if isinstance(value, png.Image):
            pass
        else:
            value = super(ImagePNG, self).validate(instance, value)
            try:
                png.Reader(value).validate_signature()
            except png.FormatError:
                self.error(instance, value, extra='Open file is not PNG.')
            value.seek(0)
        # Write input to new bytestream
        output = BytesIO()
        output.name = self.filename
        output.__valid__ = True
        if isinstance(value, png.Image):
            value.save(output)
        else:
            fid = value
            fid.seek(0)
            output.write(fid.read())
            fid.close()
        output.seek(0)
        return output
项目:codingTheMatrix    作者:RestrictedZone    | 项目源码 | 文件源码
def file2image(path):
    """ Reads an image into a list of lists of pixel values (tuples with
        three values). This is a color image. """
    (w, h, p, m) = png.Reader(filename = path).asRGBA() # force RGB and alpha
    return [_flat2boxed(r) for r in p]
项目:codingTheMatrix    作者:RestrictedZone    | 项目源码 | 文件源码
def file2image(path):
    """ Reads an image into a list of lists of pixel values (tuples with
        three values). This is a color image. """
    (w, h, p, m) = png.Reader(filename = path).asRGBA() # force RGB and alpha
    return [_flat2boxed(r) for r in p]
项目:codingTheMatrix    作者:RestrictedZone    | 项目源码 | 文件源码
def file2image(path):
    """ Reads an image into a list of lists of pixel values (tuples with
        three values). This is a color image. """
    (w, h, p, m) = png.Reader(filename = path).asRGBA() # force RGB and alpha
    return [_flat2boxed(r) for r in p]
项目:codingTheMatrix    作者:RestrictedZone    | 项目源码 | 文件源码
def file2image(path):
    """ Reads an image into a list of lists of pixel values (tuples with
        three values). This is a color image. """
    (w, h, p, m) = png.Reader(filename = path).asRGBA() # force RGB and alpha
    return [_flat2boxed(r) for r in p]
项目:codingTheMatrix    作者:RestrictedZone    | 项目源码 | 文件源码
def file2image(path):
    """ Reads an image into a list of lists of pixel values (tuples with
        three values). This is a color image. """
    (w, h, p, m) = png.Reader(filename = path).asRGBA() # force RGB and alpha
    return [_flat2boxed(r) for r in p]
项目:fondamentibook    作者:xelatihy    | 项目源码 | 文件源码
def load(self, filename):
        '''Carica l'immagine dal file filename'''
        with open(filename,'rb') as f:
            r = png.Reader(file=f)
            iw, ih, png_img, _ = r.asRGB8()
            img = []
            for png_row in png_img:
                row = []
                for i in range(0,len(png_row),3):
                    row.append( Color(png_row[i+0],
                        png_row[i+1],png_row[i+2]) )
                img.append( row )
项目:ructf-2017-tasks    作者:HackerDom    | 项目源码 | 文件源码
def main(filename):
    width, height, pixels, meta = png.Reader(filename=filename).read()
    image_bytes = open(filename, "rb").read()
    all_idat_pos = tpng.find_list_in_list(image_bytes, b'IDAT')
    if len(all_idat_pos) != 1:
        raise Exception(f"IDAT count is {len(all_idat_pos)}")
    idat_pos = all_idat_pos[0]
    original_idat_len = struct.unpack("!I", image_bytes[idat_pos - 4: idat_pos])[0]
    idat_content = image_bytes[idat_pos + 4: idat_pos + 4 + original_idat_len]
    uncompressed = zlib.decompress(idat_content)
    filter_bytes = [uncompressed[i * (len(uncompressed) // height)] for i in range(0, height)]
    result = decode5(filter_bytes)
    result_str = ''.join(chr(i) for i in result)
    print(f'"{result_str}"')
项目:ructf-2017-tasks    作者:HackerDom    | 项目源码 | 文件源码
def write_idat_with_flag(encoded_flag, original_image_file_name, outfile):
    reader = png.Reader(filename=original_image_file_name)
    width, height, pixels, meta = reader.read()
    if height != len(encoded_flag):
        raise Exception(f"Encoded flag length {len(encoded_flag)} is not equal to height {height}")
    scanlines = list(pixels)
    filtered_scanlines = []
    for i in range(0, height):
        filtered_scanlines.append(
            png.filter_scanline(encoded_flag[i], scanlines[i], meta['planes'], scanlines[i - 1] if i > 0 else None))
    compressed = zlib.compress(b''.join(filtered_scanlines))
    png.write_chunk(outfile, b'IDAT', compressed)
项目:R11-psp-english    作者:dreambottle    | 项目源码 | 文件源码
def pngsToRawGlyphBlock(blockSize, pngPath0, pngPath1):
  rawData = bytearray(blockSize)
  r0 = png.Reader(filename=pngPath0)
  r1 = png.Reader(filename=pngPath1)
  pngMaps = (r0.read(), r1.read())

  if (pngMaps[0][0] != pngMaps[1][0]) or (pngMaps[0][1] != pngMaps[1][1]):
    print("Dimensions mismatch between {0} and {1}".format(pngPath0, pngPath1))
    exit(1)
  if pngMaps[0][3]['bitdepth'] != 2 or pngMaps[1][3]['bitdepth'] != 2:
    print("Bitdepth must be 2! (files: {0} {1})".format(pngPath0, pngPath1))
    exit(1)

  BPP = 2
  w = pngMaps[0][0]
  h = pngMaps[0][1]
  bytesPerLineImg = (2 * w * BPP) // 8
  bytesPerLineBlock = blockSize // h
  pixels = (list(pngMaps[0][2]), list(pngMaps[1][2]))
  for l in range(h):
    for nbyte in range(bytesPerLineImg):
      npx = nbyte * 2
      # lo to hi
      px = [
        pixels[0][l][npx],
        pixels[1][l][npx],
        pixels[0][l][npx+1],
        pixels[1][l][npx+1]
      ]
      byte = 0
      # doing the magic conversion and packing into a byte
      for i, p in enumerate(px): byte |= magicPxConvert(p) << 2*i
      rawData[l*bytesPerLineBlock+nbyte] = byte
  return rawData
项目:openbadges-bakery    作者:concentricsky    | 项目源码 | 文件源码
def unbake(imageFile):
    """
    Return the openbadges content contained in a baked PNG file.
    If this doesn't work, return None.

    If there is both an iTXt and tEXt chunk with keyword openbadges,
    the iTXt chunk content will be returned.
    """

    reader = png.Reader(file=imageFile)
    for chunktype, content in reader.chunks():
        if chunktype == 'iTXt' and content.startswith(b'openbadges\x00'):
            return re.sub(b'openbadges[\x00]+', b'', content).decode('utf8')
        elif chunktype == 'tEXt' and content.startswith(b'openbadges\x00'):
            return content.split('\x00')[1].decode('utf8')
项目:deploy-marathon-bluegreen    作者:softonic    | 项目源码 | 文件源码
def validate_png(filename):
    """Validate file as a png image. Throws a DCOSException if it is not an PNG

    :param filename: path to the image
    :type filename: str
    :rtype: None
    """

    try:
        png.Reader(filename=filename).validate_signature()
    except Exception as e:
        logger.exception(e)
        raise DCOSException(
            'Unable to validate [{}] as a PNG file'.format(filename))
项目:3dstools    作者:ObsidianX    | 项目源码 | 文件源码
def load(self, filename):
        bmp = []

        if self.has_cv:
            img = cv2.imread(filename, CV2_READ_ALPHA)

            height, width, channels = img.shape
            if self.swizzle == SWIZZLE_ROT_90:
                img = self._rotate_image(img, -90, width, height)
                height_ = height

                height = width
                width = height_

            elif self.swizzle == SWIZZLE_TRANSPOSE:
                cv2.flip(img, 0, dst=img)
                img = self._rotate_image(img, -90, width, height)
                height_ = height

                height = width
                width = height_

            for y in range(height):
                for x in range(width):
                    # OpenCV keeps a BGRA format internally so swap R and B
                    bgra = list(img[y][x])
                    b = bgra[0]
                    bgra[0] = bgra[2]
                    bgra[2] = b

                    bmp.append(bgra)
        else:
            png_file = open(filename, 'rb')
            reader = png.Reader(file=png_file)
            width, height, pixels, metadata = reader.read()
            png_file.close()

            for row in list(pixels):
                for pixel in range(len(row) / 4):
                    bmp.append(row[pixel * 4:pixel * 4 + 4])

        self.imag = {
            'width': width,
            'height': height,
            'format': FORMAT_RGBA8
        }

        self.order = '>' if self.big_endian else '<'

        self.bmp = self._parse_image_data(bmp, to_bin=True, exact=False)