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

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

项目:CNN-Glasses-Remover    作者:JubilantJerry    | 项目源码 | 文件源码
def generate(width, height, s, output):
    canvas = np.zeros((height, width), dtype='float64')
    max_d = math.sqrt(width**2 + height**2) / 2
    offset_angular = 0
    if (width >= height):
        offset_angular = math.pi / 4
    for (i, j), _ in np.ndenumerate(canvas):
        y = height // 2 - i
        x = j - width // 2
        d = math.sqrt(x**2 + y**2)
        t = math.atan2(y, x)
        canvas[i,j] = (255 / 4) * \
            (2 + radial_sin(d, s, t) + angular_sin (
                d, t, max_d, s, offset_angular))
    f = open(output, 'wb')
    w = png.Writer(width, height, greyscale=True)
    w.write(f, canvas)
    f.close()
项目:aws-greengrass-mini-fulfillment    作者:awslabs    | 项目源码 | 文件源码
def save_PNG(self, filename, rws):
        # print("[save_PNG] filename:{0} rws:{1}".format(filename, rws))
        name = 'img/{0}'.format(filename)
        f = open(name, 'wb')
        w = png.Writer(96, 96, greyscale=True)
        w.write(f, rws)
        f.close()
        return name
项目:conway    作者:avyfain    | 项目源码 | 文件源码
def to_png(board, square_size=DEFAULT_SQUARE_SIZE):
    """
    Serializes the board as a png file.
    """
    png_size = (board.size + 1)*square_size
    writer = png.Writer(png_size, png_size, greyscale=True, bitdepth=1)

    lines = board.scale(square_size)
    board.frame_num += 1
    frame_name = '{}.png'.format(board.frame_num)
    with open(frame_name, 'wb') as frame:
        writer.write(frame, lines)
项目:django-corenlp    作者:arunchaganty    | 项目源码 | 文件源码
def log_image(self, step, tag, val):
        '''
        Write an image event.

        :param int step: Time step (x-axis in TensorBoard graphs)
        :param str tag: Label for this value
        :param numpy.ndarray val: Image in RGB format with values from
            0 to 255; a 3-D array with index order (row, column, channel).
            `val.shape[-1] == 3`
        '''
        # TODO: support floating-point tensors, 4-D tensors, grayscale
        if len(val.shape) != 3:
            raise ValueError('`log_image` value should be a 3-D tensor, instead got shape %s' %
                             (val.shape,))
        if val.shape[2] != 3:
            raise ValueError('Last dimension of `log_image` value should be 3 (RGB), '
                             'instead got shape %s' %
                             (val.shape,))
        fakefile = StringIO()
        png.Writer(size=(val.shape[1], val.shape[0])).write(
            fakefile, val.reshape(val.shape[0], val.shape[1] * val.shape[2]))
        encoded = fakefile.getvalue()
        # https://tensorflow.googlesource.com/tensorflow/+/master/tensorflow/core/framework/summary.proto
        RGB = 3
        image = Summary.Image(height=val.shape[0], width=val.shape[1],
                              colorspace=RGB, encoded_image_string=encoded)
        summary = Summary(value=[Summary.Value(tag=tag, image=image)])
        self._add_event(step, summary)
项目:django-corenlp    作者:arunchaganty    | 项目源码 | 文件源码
def log_image(self, step, tag, val):
        '''
        Write an image event.

        :param int step: Time step (x-axis in TensorBoard graphs)
        :param str tag: Label for this value
        :param numpy.ndarray val: Image in RGB format with values from
            0 to 255; a 3-D array with index order (row, column, channel).
            `val.shape[-1] == 3`
        '''
        # TODO: support floating-point tensors, 4-D tensors, grayscale
        if len(val.shape) != 3:
            raise ValueError('`log_image` value should be a 3-D tensor, instead got shape %s' %
                             (val.shape,))
        if val.shape[2] != 3:
            raise ValueError('Last dimension of `log_image` value should be 3 (RGB), '
                             'instead got shape %s' %
                             (val.shape,))
        fakefile = StringIO()
        png.Writer(size=(val.shape[1], val.shape[0])).write(
            fakefile, val.reshape(val.shape[0], val.shape[1] * val.shape[2]))
        encoded = fakefile.getvalue()
        # https://tensorflow.googlesource.com/tensorflow/+/master/tensorflow/core/framework/summary.proto
        RGB = 3
        image = Summary.Image(height=val.shape[0], width=val.shape[1],
                              colorspace=RGB, encoded_image_string=encoded)
        summary = Summary(value=[Summary.Value(tag=tag, image=image)])
        self._add_event(step, summary)
项目:codingTheMatrix    作者:RestrictedZone    | 项目源码 | 文件源码
def image2file(image, path):
    """ Writes an image in list of lists format to a file. Will work with
        either color or grayscale. """
    if isgray(image):
        img = gray2color(image)
    else:
        img = image
    with open(path, 'wb') as f:
        png.Writer(width=len(image[0]), height=len(image)).write(f,
            [_boxed2flat(r) for r in img])

## Display functions
项目:codingTheMatrix    作者:RestrictedZone    | 项目源码 | 文件源码
def image2file(image, path):
    """ Writes an image in list of lists format to a file. Will work with
        either color or grayscale. """
    if isgray(image):
        img = gray2color(image)
    else:
        img = image
    with open(path, 'wb') as f:
        png.Writer(width=len(image[0]), height=len(image)).write(f,
            [_boxed2flat(r) for r in img])

## Display functions
项目:codingTheMatrix    作者:RestrictedZone    | 项目源码 | 文件源码
def image2file(image, path):
    """ Writes an image in list of lists format to a file. Will work with
        either color or grayscale. """
    if isgray(image):
        img = gray2color(image)
    else:
        img = image
    with open(path, 'wb') as f:
        png.Writer(width=len(image[0]), height=len(image)).write(f,
            [_boxed2flat(r) for r in img])

## Display functions
项目:codingTheMatrix    作者:RestrictedZone    | 项目源码 | 文件源码
def image2file(image, path):
    """ Writes an image in list of lists format to a file. Will work with
        either color or grayscale. """
    if isgray(image):
        img = gray2color(image)
    else:
        img = image
    with open(path, 'wb') as f:
        png.Writer(width=len(image[0]), height=len(image)).write(f,
            [_boxed2flat(r) for r in img])

## Display functions
项目:codingTheMatrix    作者:RestrictedZone    | 项目源码 | 文件源码
def image2file(image, path):
    """ Writes an image in list of lists format to a file. Will work with
        either color or grayscale. """
    if isgray(image):
        img = gray2color(image)
    else:
        img = image
    with open(path, 'wb') as f:
        png.Writer(width=len(image[0]), height=len(image)).write(f,
            [_boxed2flat(r) for r in img])

## Display functions
项目:mrflow    作者:jswulff    | 项目源码 | 文件源码
def flow_write_png(u,v,fpath,valid=None):
    """
    Write KITTI optical flow.

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


    if valid==None:
        valid_ = np.ones(u.shape,dtype='uint16')
    else:
        valid_ = valid.astype('uint16')



    u_ = ((u*64.0)+2**15).astype('uint16')
    v_ = ((v*64.0)+2**15).astype('uint16')

    I = np.dstack((u_,v_,valid_))

    W = png.Writer(width=u.shape[1],
                   height=u.shape[0],
                   bitdepth=16,
                   planes=3)

    with open(fpath,'wb') as fil:
        W.write(fil,I.reshape((-1,3*u.shape[1])))
项目:kiwiclient    作者:dev-zzo    | 项目源码 | 文件源码
def _flush_rows(self):
        if not self._rows:
            return
        while True:
            with open(self._output_name + '.png', 'wb') as fp:
                try:
                    png.Writer(len(self._rows[0]), len(self._rows), greyscale=True).write(fp, self._rows)
                    break
                except KeyboardInterrupt:
                    pass
        # DUMP POINT
        if self._options.dump_histo:
            dump_to_csv(self._output_name + '-hh.csv', self._histoa.get(), 'w')
            dump_to_csv(self._output_name + '-hh.csv', self._histob.get(), 'a')
项目:single-image-depth-estimation    作者:liuhyCV    | 项目源码 | 文件源码
def convert_nyu_16bit_image(path, target_dataset_directory):
    print("load dataset: %s" % (path))
    print("target dataset dir: %s" % (target_dataset_directory))

    f = h5py.File(path)

    for i, (image, depth) in enumerate(zip(f['images'], f['depths'])):

        ra_image = image.transpose(2, 1, 0)
        ra_depth = depth.transpose(1, 0) * 100

        re_depth = (ra_depth/np.max(ra_depth))*255.0

        image_pil = Image.fromarray(np.uint8(ra_image))
        depth_pil = Image.fromarray(np.uint8(re_depth))
        image_name = os.path.join(target_dataset_directory, "%05d_img.png" % (i))
        image_pil.save(image_name)
        depth_name = os.path.join(target_dataset_directory, "%05d_dep.png" % (i))
        depth_pil.save(depth_name)

        depth_meters_name = os.path.join(target_dataset_directory, "%05d_dep_meters.png" % (i))
        with open(depth_meters_name, 'wb') as f:
            writer = png.Writer(width=ra_depth.shape[1], height=ra_depth.shape[0], bitdepth=16, greyscale=True)
            zgray2list = ra_depth.tolist()
            writer.write(f, zgray2list)

        print(i)
项目:steno3dpy    作者:aranzgeo    | 项目源码 | 文件源码
def text_png(text, scale=3):
        """Returns an open png image file with text written

        Only letters, numbers, -, >, and < are allowed. New lines are
        indicated by /
        """
        text = text.split('/')
        text_out = ['']
        for t in text:
            text_line = ['1', '1', '1', '1', '1']
            for letter in t:
                for i in range(5):
                    text_line[i] += LETTERS[letter.upper()][i] + '1'
            text_out += text_line
            text_out += ['']
        text_len = max([len(t) for t in text_out])
        text_out = [line + (text_len-len(line))*'1' for line in text_out]
        img = []
        for line in text_out:
            im_line = ''
            for n in line:
                im_line += scale*n
            img += scale*[im_line]
        png_file = NamedTemporaryFile('wb+', suffix='.png')
        png_writer = png.Writer(len(img[0]), len(img), greyscale=True, bitdepth=1)
        png_writer.write(png_file, img)
        png_file.seek(0)
        return png_file
项目:mcm-tools    作者:savaga    | 项目源码 | 文件源码
def parse_font(data, ofile, draw_net = False):
    img_x = 192
    img_y = 288
    if draw_net:
        img_x += 15
        img_y += 15
    img = png.Writer(img_x, img_y)#, greyscale=True)
    img_list = []
    i = 0
    for char_row in xrange(0, 256, 16):
        for ch_row in xrange(0, 54, 3):
            img_line = []
            for char_col in xrange(16):
                char_line = []
                for pix in xrange(2,-1,-1):
                    byte = data[char_col + char_row][ch_row + pix]
                    byte = byte[::-1]
                    for bit in xrange(0, 8, 2):
                        if byte[bit:bit+2] == '01':
                            char_line.extend([255,255,255])
                        elif byte[bit:bit+2] == '00':
                            char_line.extend([0,0,0])
                        elif byte[bit:bit+2] == '10':
                            char_line.extend([128, 128, 128])
                        else:
                            print byte[bit:bit+2]
                        i += 1

                img_line.extend(char_line[::-1])
                if draw_net and char_col < 15:
                    img_line.extend([255,0,0])
            img_list.append(tuple(img_line))
        if draw_net and char_row < 240:
            img_list.append([255,0,0]*img_x)
    img.write(ofile, img_list)
项目:WDBRipper    作者:LiamBrandt    | 项目源码 | 文件源码
def export_gif(image, path, bin_file, pretext=""):
    """
    Create a PNG image based on a GIF image.

    The GIF data is specified in the dictionary image and contains formatted
    data based on the wdb structure. The PNG image is saved to path.
    """
    gif_name = get_raw(image["gif_name"], bin_file)
    width = get_raw(image["width"], bin_file)
    height = get_raw(image["height"], bin_file)
    num_colors = get_raw(image["num_colors"], bin_file)

    colors = []
    for color in image["colors"]:
        r = get_raw(color["r"], bin_file)
        g = get_raw(color["g"], bin_file)
        b = get_raw(color["b"], bin_file)
        colors.append((r, g, b))

    rows = []
    y = 0
    for row in image["rows"]:
        x = 0
        rows.append([])
        for pixel in row["pixels"]:
            color_index = get_raw(pixel["color_index"], bin_file)
            c = colors[color_index]
            for i in range(3):
                rows[y].append(c[i])

            x += 1
        y += 1

    #write png
    f = open(path + "/" + pretext + gif_name[:-4] + ".png", "wb")
    f.truncate()
    w = png.Writer(width, height)
    w.write(f, rows)
    f.close()
项目:PyDDS    作者:dph119    | 项目源码 | 文件源码
def write_to_png(self, fname):
        """Write out the pixel data to a .png file."""

        # Figure out which data to write out.
        # If the decompressed data is valid, use that.
        if self.data_is_decompressed:
            data = self.decompressed_data
        else:
            data = self.data

        assert data, 'data must be something valid at this point.'

        # Check to see if the data contains mipmaps
        # If it does, truncate out everything beyond mip0
        # TODO: Eventually add support to specify which mip level to write out
        if self.dds_header.dwMipMapCount > 0:
            # Calculate the size of mip 0 in bytes
            # (number of pixels in mip0) * (bytes/pixel)
            mip0_size = self.dds_header.dwWidth * self.dds_header.dwHeight * 4
            data = data[:mip0_size]

        self.logger.info('Creating PNG file: %s (width, height = %d,%d)', \
                         fname, self.dds_header.dwWidth, self.dds_header.dwHeight)

        fhandle = open(fname, 'wb')
        swizzled_data = self.swizzle_decompressed_bc1_to_png(data, self.dds_header.dwWidth)

        # TODO: Check if alpha really does exist in original data. Currently assuming it always does.
        writer = png.Writer(self.dds_header.dwWidth, self.dds_header.dwHeight, alpha=True)

        # PNG expects the data to be presented in "boxed row flat pixel" format:
        # list([R,G,B,A  R,G,B,A  R,G,B,A],
        #      [R,G,B,A  R,G,B,A  R,G,B,A])
        # Each row will be width * # components elements * # bytes/component
        formatted_data = zip(*(iter(swizzled_data),) * (self.dds_header.dwWidth * 4 * 1))

        writer.write(fhandle, formatted_data)
        fhandle.close()

        self.logger.info('Done creating PNG file.')
项目:ice    作者:kbrsh    | 项目源码 | 文件源码
def generateImage():
    data = []
    rowsSlope = 2.0 / (float(rows) - 1.0)
    colsSlope = 2.0 / (float(cols) - 1.0)
    pixelOperationC1 = pixel[0]
    pixelOperationC2 = pixel[1]
    pixelOperationC3 = pixel[2]
    pixelColor = pixel[3]

    for row in range(rows):
        currentRow = []
        x = (rowsSlope * float(row)) - 1.0

        for col in range(cols):
            y = (colsSlope * float(col)) - 1.0
            (c1, c2, c3) = pixelColor(pixelOperationC1.compute(x, y), pixelOperationC2.compute(x, y), pixelOperationC3.compute(x, y))

            currentRow.append(c1)
            currentRow.append(c2)
            currentRow.append(c3)

        data.append(currentRow)

    f = open("art.png", "wb")
    w = png.Writer(cols, rows)
    w.write(f, data)
    f.close()

# Generate
项目:pollenapp    作者:Jugendhackt    | 项目源码 | 文件源码
def erzeuge_pollenkarte(matrix):
    breite = len(matrix)
    hoehe = len(matrix[0])

    matrix2 = []
    for x in range(breite):
        zeile = []
        for y in range(hoehe):
            wert = matrix[x][y]
            #rgba = (wert, wert, wert, 0.1)
            #zeile.append(rgba)
            zeile.append(0xCC)
            zeile.append(0)
            zeile.append(0)
            zeile.append(wert)
        matrix2.append(zeile)

    image = png.from_array(matrix2, 'RGBA')

    image.save('pollenkarte.png')

#    png_file = open('pollenkarte.png', 'wb')
#    png_writer = png.Writer(width=breite, height=hoehe, alpha=True, bitdepth=8)
#            #greyscale=True,
#    #for daten in matrix:
#    #    png_writer.write(png_file, daten)
#    png_writer.write(png_file, matrix2)
#    png_file.close()
项目:csgm    作者:AshishBora    | 项目源码 | 文件源码
def save_image(image, path):
    """Save an image as a png file"""
    png_writer = png.Writer(28, 28, greyscale=True)
    with open(path, 'wb') as outfile:
        png_writer.write(outfile, 255*image)
项目:csgm    作者:AshishBora    | 项目源码 | 文件源码
def save_image(image, path):
    """Save an image as a png file"""
    image = dcgan_utils.inverse_transform(image)
    png_writer = png.Writer(64, 64)
    with open(path, 'wb') as outfile:
        png_writer.write(outfile, 255*image.reshape([64,-1]))
项目:snetRenderer    作者:shubhtuls    | 项目源码 | 文件源码
def saveUint16(z, path):
    # Use pypng to write zgray as a grayscale PNG.
    with open(path, 'wb') as f:
        writer = png.Writer(width=z.shape[1], height=z.shape[0], bitdepth=16, greyscale=True)
        zgray2list = z.tolist()
        writer.write(f, zgray2list)
项目:DeltaPicker    作者:T-Kuhn    | 项目源码 | 文件源码
def savePNG(self, filename, rws):
        print 'saving the PNG'
        f = open(string.join(['img/', str(self.folderName), filename]), 'wb')
        w = png.Writer(self.proccessingHeight, self.proccessingWidth, greyscale=True)
        w.write(f, rws) 
        f.close()

    # - - - - - - - - - - - - - - - - 
    # - - - BLINK CAMERA LED  - - - -
    # - - - - - - - - - - - - - - - -
项目:properties    作者:aranzgeo    | 项目源码 | 文件源码
def test_png(self):

        dirname, _ = os.path.split(os.path.abspath(__file__))
        png_file = os.path.sep.join(dirname.split(os.path.sep) + ['temp.png'])
        s = ['110010010011',
             '101011010100',
             '110010110101',
             '100010010011']
        f = open(png_file, 'wb')
        w = png.Writer(len(s[0]), len(s), greyscale=True, bitdepth=16)
        w.write(f, s)
        f.close()

        with self.assertRaises(TypeError):
            properties.ImagePNG('bad filename', filename=False)

        class HasPNG(properties.HasProperties):
            myimage = properties.ImagePNG('my image', filename='img.png')

        hpng = HasPNG()
        with self.assertRaises(ValueError):
            hpng.myimage = False
        with self.assertRaises(ValueError):
            hpng.myimage = properties.__file__

        hpng.myimage = png_file
        assert isinstance(hpng.myimage, BytesIO)
        json_0 = properties.ImagePNG.to_json(hpng.myimage)

        hpng.myimage = open(png_file, 'rb')
        assert isinstance(hpng.myimage, BytesIO)
        json_1 = properties.ImagePNG.to_json(hpng.myimage)
        hpng.myimage = hpng.myimage
        assert isinstance(hpng.myimage, BytesIO)

        hpng.myimage = png.from_array(s, 'L;16')
        assert isinstance(hpng.myimage, BytesIO)
        json_2 = properties.ImagePNG.to_json(hpng.myimage)

        assert json_0 == json_1
        assert json_0 == json_2

        hpng.myimage = properties.ImagePNG.from_json(json_0)
        assert isinstance(hpng.myimage, BytesIO)

        with self.assertRaises(ValueError):
            properties.ImagePNG.from_json('pretty picture')

        os.remove(png_file)
项目:citra_system_archives    作者:B3n30    | 项目源码 | 文件源码
def extract(self):
        basename_ = os.path.splitext(os.path.basename(self.filename))[0]

        glyph_widths = {}
        for cwdh in self.cwdh_sections:
            for index in range(cwdh['start'], cwdh['end'] + 1):
                glyph_widths[index] = cwdh['data'][index - cwdh['start']]

        glyph_mapping = {}
        for cmap in self.cmap_sections:
            if cmap['type'] == MAPPING_DIRECT:
                for code in range(cmap['start'], cmap['end']):
                    glyph_mapping[unichr(code)] = code - cmap['start'] + cmap['indexOffset']
            elif cmap['type'] == MAPPING_TABLE:
                for code in range(cmap['start'], cmap['end']):
                    index = cmap['indexTable'][code - cmap['start']]
                    if index != 0xFFFF:
                        glyph_mapping[unichr(code)] = index
            elif cmap['type'] == MAPPING_SCAN:
                for code in cmap['entries'].keys():
                    glyph_mapping[code] = cmap['entries'][code]

        # save JSON manifest
        json_file_ = open('%s_manifest.json' % basename_, 'w')
        json_file_.write(json.dumps({
            'fontInfo': self.font_info,
            'textureInfo': {
                'glyph': self.tglp['glyph'],
                'sheetCount': self.tglp['sheetCount'],
                'sheetInfo': {
                    'cols': self.tglp['sheet']['cols'],
                    'rows': self.tglp['sheet']['rows'],
                    'width': self.tglp['sheet']['width'],
                    'height': self.tglp['sheet']['height'],
                    'colorFormat': PIXEL_FORMATS[self.tglp['sheet']['format']]
                }
            },
            'glyphWidths': glyph_widths,
            'glyphMap': glyph_mapping
        }, indent=2, sort_keys=True))
        json_file_.close()

        # save sheet bitmaps
        for i in range(self.tglp['sheetCount']):
            sheet = self.tglp['sheets'][i]
            width = sheet['width']
            height = sheet['height']
            png_data = []
            for y in range(height):
                row = []
                for x in range(width):
                    for color in sheet['data'][x + (y * width)]:
                        row.append(color)

                png_data.append(row)

            file_ = open('%s_sheet%d.png' % (basename_, i), 'wb')
            writer = png.Writer(width, height, alpha=True)
            writer.write(file_, png_data)
            file_.close()
项目:3dstools    作者:ObsidianX    | 项目源码 | 文件源码
def extract(self):
        width = self.imag['width']
        height = self.imag['height']

        png_data = []
        for y in range(height):
            row = []
            for x in range(width):
                pos = x + (y * width)
                if self.has_cv:
                    # OpenCV keeps a BGRA format internally so swap R and B
                    rgba = list(self.bmp[pos])
                    r = rgba[0]
                    rgba[0] = rgba[2]
                    rgba[2] = r

                    row.append(rgba)
                else:
                    for color in self.bmp[x + (y * width)]:
                        row.append(int(color))
            png_data.append(row)

        basename = os.path.splitext(os.path.basename(self.filename))[0]
        filename = '%s.png' % basename

        if self.has_cv:
            img = numpy.array(png_data, dtype=numpy.uint8)

            swizzle = self.imag['swizzle']
            if swizzle == SWIZZLE_ROT_90:
                img = self._rotate_image(img, 90, width, height)
            elif swizzle == SWIZZLE_TRANSPOSE:
                # the lazy transpose... rotate and flip one axis
                img = self._rotate_image(img, 90, width, height)
                cv2.flip(img, 0, dst=img)
            cv2.imwrite(filename, img)
        else:
            file_ = open(filename, 'wb')
            writer = png.Writer(width, height, alpha=True)
            writer.write(file_, png_data)
            file_.close()

    # OpenCV doesn't resize around the center when rotating (since it's just working with matrices)
    # so we need to do some lame canvas work to ensure a clean rotation + resize around the center
项目:R11-psp-english    作者:dreambottle    | 项目源码 | 文件源码
def writePngs(font, firstHalfHack=False):
  # out = 'font00.png'
  raw = font.imageRawData

  bs = font.header.blockSize
  h = font.header.height
  w = font.header.width
  wb = bs // h
  BPP = 2

  glyphs = []
  for i in range(len(raw) // bs):
    pos = i * bs
    rawBlock = raw[pos:pos+bs]
    # 2 glyphs in every block
    glyph0 = []
    glyph1 = []
    for l in range(h):
      rawLine = rawBlock[ l*wb : l*wb+wb ]

      line0 = []
      line1 = []
      rng = wb
      if firstHalfHack:
        rng //= 2
      for p in range(rng):
        # byte = rawLine[p]
        # px = ((byte & 1) << 1) | ((byte >> 1) & 1)
        # line0.append(px)
        # byte >>= 2
        # px = ((byte & 1) << 1) | ((byte >> 1) & 1)
        # line1.append(px)
        # byte >>= 2
        # px = ((byte & 1) << 1) | ((byte >> 1) & 1)
        # line0.append(px)
        # byte >>= 2
        # px = ((byte & 1) << 1) | ((byte >> 1) & 1)
        # line1.append(px)
        # Nope, let's try sth different

        loHalf = rawLine[p] & 0xF
        hiHalf = rawLine[p] >> 4 & 0xF
        px0 = loHalf & 0x3
        line0.extend([magicPxConvert(loHalf & 0x3), magicPxConvert(hiHalf & 0x3)])
        line1.extend([magicPxConvert(loHalf >> 2), magicPxConvert(hiHalf >> 2)])
      glyph0.append(line0)
      glyph1.append(line1)
    # every block
    glyphs.append(glyph0)
    glyphs.append(glyph1)

  print("decoded glyphs count:", len(glyphs))
  print("Writing glyphs to files...")
  writer = png.Writer(w, h, greyscale=True, bitdepth=2)
  for i in range(0, len(glyphs)):
    file = open('glyphs/{0:d}.png'.format(i), 'wb')
    writer.write(file, glyphs[i])
    file.close()


# Works both ways (encode & decode). I still have no idea why they did it though.
项目:Py-EntityMap3    作者:Akhier    | 项目源码 | 文件源码
def _clean_up_last_ring(self, ring):
        print('starting clean up of last ring')
        while ring:
            random.shuffle(ring)
            currentroom = ring.pop()
            shortestdist = 20
            closestroom = False
            for room in ring:
                dist = math.hypot(room.X - currentroom.X,
                                  room.Y - currentroom.Y)
                if dist < shortestdist:
                    shortestdist = dist
                    closestroom = room
            if closestroom:
                xdist = math.hypot(currentroom.X - closestroom.X, 0)
                ydist = math.hypot(0, currentroom.Y - closestroom.Y)
                hall = get_line(currentroom.Center, closestroom.Center)
                if xdist > ydist:
                    hall.extend(get_line((currentroom.X + 1, currentroom.Y),
                                         (closestroom.X + 1, closestroom.Y)))
                else:
                    hall.extend(get_line((currentroom.X, currentroom.Y + 1),
                                         (closestroom.X, closestroom.Y + 1)))
                newhall = _room(0, 1, 1, (0, 0))
                newhall.Tiles = hall
                self.rooms.append(newhall)
                if self.debug:
                    coords = {}
                    for value in newhall.Tiles:
                        coords[value] = True
                    with open('PNGoutput/' +
                              format(self.currentpng, '04d') +
                              '.png', 'wb') as f:
                        w = png.Writer(self.width, self.height,
                                       alpha=True)
                        templist = []
                        for y in range(self.height):
                            innerlist = []
                            for x in range(self.width):
                                if (x, y) in coords:
                                    innerlist.append(self.ccR)
                                    innerlist.append(self.ccG)
                                    innerlist.append(self.ccB)
                                    innerlist.append(255)
                                else:
                                    innerlist.append(0)
                                    innerlist.append(0)
                                    innerlist.append(0)
                                    innerlist.append(0)
                            templist.append(innerlist)
                        w.write(f, templist)
                    self.color_change()
                    self.currentpng = self.currentpng + 1