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

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

项目:tensorflow_dqn_supermario    作者:JSDanielPark    | 项目源码 | 文件源码
def replay_train(self, mainDQN, targetDQN, train_batch):
        x_stack = np.empty(0).reshape(0, self.input_size)
        y_stack = np.empty(0).reshape(0, self.output_size)
        step = 0
        for state, action, reward, next_state, done in train_batch:
            Q = mainDQN.predict(state)
            #png.from_array(next_state, 'L').save('capture/' + str(step) + '.png')

            if done:
                Q[0, action] = reward
            else:
                Q[0, action] = reward + self.dis * targetDQN.predict(next_state)[0, np.argmax(mainDQN.predict(next_state))]


            state = np.reshape(state, [self.input_size])
            y_stack = np.vstack([y_stack, Q])
            x_stack = np.vstack([x_stack, state])
            step += 1

        return mainDQN.update(x_stack, y_stack)
项目:PyMaid    作者:schlegelp    | 项目源码 | 文件源码
def screenshot(file='screenshot.png', alpha=True):
    """ Saves a screenshot of active 3D canvas.

    Parameters
    ----------
    file :      str, optional
                Filename
    alpha :     bool, optional
                If True, alpha channel will be saved
    """
    if alpha:
        mode = 'RGBA'
    else:
        mode = 'RGB'

    im = png.from_array(_screenshot(alpha=alpha), mode=mode)
    im.save(file)

    return
项目:tanks-of-freedom-server    作者:P1X-in    | 项目源码 | 文件源码
def create_map(map_code, map_data):
    """Method for creating map image."""
    if map_image_exists(map_code):
        return

    file_path = get_file_path(map_code)

    image_matrix = generate_base_image_matrix()
    image_matrix = fill_matrix_with_data(image_matrix, map_data)

    image = png.from_array(image_matrix, "RGB")
    image.save(file_path)
项目:BrundleFuzz    作者:carlosgprado    | 项目源码 | 文件源码
def main():
    if len(sys.argv) != 2:
        print "python %s <filename>" % sys.argv[0]
        sys.exit(1)

    try:
        filename = sys.argv[1]
        with open(filename, 'rb') as f:
            saved_state = pickle.load(f)

        bitmap = saved_state['bitmap']

    except:
        print "[!] Could not load bitmap"
        sys.exit(1)

    # Get rough code coverage value
    coverage = get_coverage(bitmap)
    print "[*] Code coverage (basic block calls): %.2f" % coverage

    if HAS_PYPNG:       
        # Create PNG image from bitmap values
        p = populate_array(bitmap)
        img = png.from_array(p, 'RGB')
        img.save('status_graph.png')

        print "[*] Created PNG file"
项目:facejack    作者:PetarV-    | 项目源码 | 文件源码
def publish_image(face_im, adv_im, combined_im, confidence=0.0, hack=False):
    """convert png; base64 encode that and post to stat server"""
    # Do face
    text_buf = io.BytesIO()
    png.from_array(face_im, 'RGB').save(text_buf)
    encoded_face = b"data:image/png;base64,"+base64.b64encode(text_buf.getvalue(),b'#/')

    # Do adv
    text_buf = io.BytesIO()
    png.from_array(adv_im, 'RGB').save(text_buf)
    encoded_adv = b"data:image/png;base64," + base64.b64encode(text_buf.getvalue(),b'#/')

    # Do combined
    text_buf = io.BytesIO()
    png.from_array(combined_im, 'RGB').save(text_buf)
    encoded_combined = b"data:image/png;base64," + base64.b64encode(text_buf.getvalue(),b'#/')

    url = "http://facejack.westeurope.cloudapp.azure.com:5000/push_stats"
    if hack:
        payload = b"adversarial=yes&original_img=" + encoded_face + \
                  b"&adv_mod_img=" + encoded_adv + \
                  b"&modified_img=" + encoded_combined + \
                  b"&confidence=" + str(confidence * 100).encode()
    else:
        payload = b"adversarial=no&original_img="+encoded_face+\
                  b"&adv_mod_img="+encoded_adv+\
                  b"&modified_img="+encoded_combined+\
                  b"&confidence="+str(confidence*100).encode()
    headers = {
        'content-type': "application/x-www-form-urlencoded",
        'cache-control': "no-cache"
    }

    response = requests.request("POST", url, data=payload, headers=headers, )
项目:fondamentibook    作者:xelatihy    | 项目源码 | 文件源码
def save(self, filename):
        '''Salva l'immagine nel file filename'''
        pixels = []
        for j in range(self.height()):
            pixels.append([])
            for i in range(self.width()):
                c = self.get_pixel(i,j)
                pixels[-1] += [c.r,c.g,c.b]
        pyimg = png.from_array(pixels, 'RGB')
        pyimg.save(filename)
项目:fondamentibook    作者:xelatihy    | 项目源码 | 文件源码
def save(filename,img):
    pyimg = png.from_array(img, 'RGB')
    pyimg.save(filename)
项目:fondamentibook    作者:xelatihy    | 项目源码 | 文件源码
def save(filename, img):
    '''Salva un'immagine in formato PNG.'''
    pyimg = png.from_array(img, 'RGB')
    pyimg.save(filename)
项目:ructf-2017-tasks    作者:HackerDom    | 项目源码 | 文件源码
def generate_original():
    height = 51
    pixels = [[[234, 215, 197] for j in range(0, int(math.ceil(height/3*5)))] for i in range(0, height)]
    png.from_array(pixels , 'RGB').save("original.png")
项目: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()
项目: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)
项目:xwd2png    作者:drj11    | 项目源码 | 文件源码
def main(argv=None):
    if argv is None:
        argv = sys.argv

    opts, args = getopt.getopt(argv[1:], 'i', ['info', 'raw'])

    options = [o for o,v in opts]

    if len(args) == 0:
        inp = binary(sys.stdin)
        out = binary(sys.stdout)
    else:
        inp = open(args[0], 'rb')
        out = None

    xwd = xwd_open(inp)

    if '-i' in options or '--info' in options:
        info = xwd.info()
        dprint(info)
        return 0

    if '--raw' in options:
        for row in xwd:
            print(*row)
        return 0

    if out is None:
        try:
            inp.name
        except AttributeError:
            out = "xwd2png_out.png"
        else:
            out = re.sub(r'(\..*|)$', '.png', inp.name)
            if out == inp.name:
                # avoid overwriting input,
                # if, for some reason,
                # input is mysteriously named: input.png
                output_name += '.png'

    format = xwd.uni_format()

    assert format == "RGB8"

    import png
    apng = png.from_array(xwd, "RGB;8")
    apng.save(out)