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)
python类from_array()的实例源码
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
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)
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"
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, )
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)
def save(filename,img):
pyimg = png.from_array(img, 'RGB')
pyimg.save(filename)
def save(filename, img):
'''Salva un'immagine in formato PNG.'''
pyimg = png.from_array(img, 'RGB')
pyimg.save(filename)
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")
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()
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)
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)