def append_png_assertion(self, badge): """ Append the assertion to a PNG file """ badge.signed = _signature chunks = list() png = Reader(bytes=badge.source.image) for chunk in png.chunks(): chunks.append(chunk) itxt_data = b'openbadges' + pack( 'BBBBB', 0, 0, 0, 0, 0) + badge.get_assertion().encode('utf-8') itxt = ('iTXt', itxt_data) chunks.insert(len(chunks) - 1, itxt) text_data = 'Comment Signed with OpenBadgesLib %s' % __version__ text = ('tEXt', text_data.encode('utf-8')) chunks.insert(len(chunks) - 1, text) for tag, data in chunks: badge.signed = badge.signed + pack("!I", len(data)) tag = tag.encode('iso8859-1') badge.signed = badge.signed + tag badge.signed = badge.signed + data checksum = crc32(tag) checksum = crc32(data, checksum) checksum &= 2**32 - 1 badge.signed = badge.signed + pack("!I", checksum)
def load_textures(): global texture texture = GL.glGenTextures(2) png_img = Reader( filename= 'D:\\0\\GitHub\\CEFET-Computacao_Grafica_2020-2\\Trab_08-Esfera_Texturizada\\mapa.png' ) w, h, pixels, metadata = png_img.read_flat() if (metadata['alpha']): modo = GL.GL_RGBA else: modo = GL.GL_RGB GL.glBindTexture(GL.GL_TEXTURE_2D, texture[0]) GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1) GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, modo, w, h, 0, modo, GL.GL_UNSIGNED_BYTE, pixels.tolist()) GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_REPEAT) GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_REPEAT) GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST) GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST) GL.glTexEnvf(GL.GL_TEXTURE_ENV, GL.GL_TEXTURE_ENV_MODE, GL.GL_DECAL)
def extract_png_assertion(file_data): png = Reader(bytes=file_data) for tag, data in png.chunks(): if tag == 'iTXt': fmt_len = len(data) - 15 # 15=len('openbadges'+pack('BBBBB')) fmt = '<10s5B%ds' % fmt_len return Assertion.decode(unpack(fmt, data)[6])
def textureTest(): help(Reader) r = Reader(file=open('tesx.png')) rgb = list(r.asRGBA()[2]) print len(rgb),len(rgb[0]) img = Image(500,500) drawTexturedTri(150,150,300,100,100,300,1,0,0,1,1,1,rgb,(255,255,0),img) img.savePpm('t.ppm')
def has_png_assertion(self, badge): png = Reader(bytes=badge.image) for tag, data in png.chunks(): if tag == 'iTXt': if data.startswith(b'openbadges'): return True return False
def test_png_file(filename: str) -> None: """ Takes the relative filename of a PNG file and draws the quadtree on top of it :param filename: :return: """ reader = Reader(filename) pngdata = reader.read() #extract file matrix = numpy.array([[y//255 for y in x] for x in list(pngdata[2])])[:, ::3] # load into numpy array lqtld = trees.LinearQuadTree(value_matrix=matrix) lqtld.draw_all_usable_cells() lqtld.generate_debug_png('../output.png')
def __readPngFile(self): with open(self._s_file, "rb") as fs: _reader = Reader(file=fs) _data = _reader.read() _colorarray = [] for frame in list(_data[2]): framearray = list(frame) _colorarray.append([ framearray[x:x + 3] for x in range(0, len(framearray), 3) ]) self.__nbleds = _data[0] self.__nbframes = _data[1] self.__data = _colorarray
def one_channel_image_reader(filepath, datatype, input_has_three_channels=True): """Labels are stored in a crude way into the png format that cannot be handled by standard libraries. Therefore, we have to create this decoder.""" im = Reader(filepath) _, _, array, _ = im.asDirect() array = np.vstack(itertools.imap(datatype, array)) if input_has_three_channels: # This image array is now in 'boxed row flat pixel' format, meaning that each row # is just a continuous list of R, G, B, R, G, B, R, ... values. # We are in this case only interested in the first component, which holds the # class label, therefore we take every third value. array = array[:, range(0, array.shape[1], 3)] return datatype(array)
def load(): global textura textura = GL.glGenTextures(2) imagem = Reader(filename='C:\\Users\\Pedro\\Desktop\\computacao grafica\\trabalhos cg 2021.1\\7 - globo textura\\globomodelo.png') w, h, pixels, metadata = imagem.read_flat() if(metadata['alpha']): mod = GL.GL_RGBA else: mod = GL.GL_RGB GL.glBindTexture(GL.GL_TEXTURE_2D, textura[0]) GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1) GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, mod, w, h, 0, mod, GL.GL_UNSIGNED_BYTE, pixels.tolist()) GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_REPEAT) GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_REPEAT) GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST) GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST) GL.glTexEnvf(GL.GL_TEXTURE_ENV, GL.GL_TEXTURE_ENV_MODE, GL.GL_DECAL)
def test_png_gen_greyscale_works(): alpha_ch = np.array([[1, 1, 1]]) gen = PngGenerator(alpha_ch, greyscale=True) img_data = np.array([[0.0, 5.0, 10.0]]) norm_img_data = (img_data - img_data.min()) / (img_data.max() - img_data.min()) img_bytes = gen.generate_png(img_data) reader = Reader(bytes=img_bytes) width, height, pixels, _ = reader.asFloat() assert_equal(width, 3) assert_equal(height, 1) grey_shape = img_data.shape + (2, ) assert_almost_equal(np.array(list(pixels)).reshape(grey_shape)[:, :, 0], norm_img_data, decimal=4)
def load_image(filename): """Given the file name of a PNG file, create and return an Image object representing the image. """ if not isfile(filename): raise ValueError("file '" + filename + "' cannot be found") reader = Reader(filename) num_cols, num_rows, pixels, _ = reader.asRGBA() rows = [] for row in pixels: # note: each 'row' from this iterator is an array, so we call # its tolist() method here and box it rows.append(_box(row.tolist(), input_type='rgba')) img = Image(num_rows, num_cols) img.image_data = rows return img
def generate_spectrogram_file(self, audio: AudioRecording): prefilter = settings.SPECTROGRAM_PREFILTER credit = settings.SPECTROGRAM_CREDIT title = '(unknown) ' if audio.species: title = f'{audio.genus} {audio.species} ' try: species = self.species_lookup.species_by_abbreviations( audio.genus, audio.species) except NonUniqueSpeciesLookup: species = None if species: species_ucfirst = species.species[0].upper( ) + species.species[1:] if species.common_name: title = f'{species.common_name} ({species.genus} {species_ucfirst}) ' else: title = f'{species.genus} {species_ucfirst} ' if audio.recorded_at_iso: title += date_parser.parse( audio.recorded_at_iso).strftime('%Y-%m-%d %H:%M') if not audio.id: audio.save() dest = os.path.join(settings.MEDIA_ROOT, 'processed', 'spectrograms', f'{audio.id}-{audio.identifier}.png') print(f'Plot {audio.audio_file} spectrum to {dest}') # sox "$file" -n spectrogram -o "$outfile" -t "$ident" sox_result = subprocess.run([ self.sox_executable, audio.audio_file, '-n', ] + prefilter + ['spectrogram', '-o', dest, '-c', credit, '-t', title]) sox_result.check_returncode() png_reader = Reader(filename=dest) (width, height, _, _) = png_reader.read() audio.spectrogram_image_file = dest audio.spectrogram_image_width = width audio.spectrogram_image_height = height
def LoadTextures(): global texture texture = GL.glGenTextures(2) ############################################################################################### reader = Reader(filename='C:\\Users\\user\\Desktop\\computação grafica\\mapa.png') w, h, pixels, metadata = reader.read_flat() if(metadata['alpha']): modo = GL.GL_RGBA else: modo = GL.GL_RGB GL.glBindTexture(GL.GL_TEXTURE_2D, texture[0]) GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1) GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, modo, w, h, 0, modo, GL.GL_UNSIGNED_BYTE, pixels.tolist()) GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_REPEAT) GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_REPEAT) GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST) GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST) GL.glTexEnvf(GL.GL_TEXTURE_ENV, GL.GL_TEXTURE_ENV_MODE, GL.GL_DECAL)
def load_textures(): global texture texture = glGenTextures(2) mapa = Reader(filename='./mapa.png') w, h, pixels, metadata = mapa.read_flat() if (metadata['alpha']): modo = GL_RGBA else: modo = GL_RGB glBindTexture(GL_TEXTURE_2D, texture[0]) glPixelStorei(GL_UNPACK_ALIGNMENT, 1) glTexImage2D(GL_TEXTURE_2D, 0, modo, w, h, 0, modo, GL_UNSIGNED_BYTE, pixels.tolist()) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL)
def main(): comm = MPI.COMM_WORLD id= comm.Get_rank() wsize= comm.Get_size() tstart = MPI.Wtime() fsky = open("skymap.png","r") reader = Reader(fsky) skypixelwidth, skypixelheight, skypixels, metadata=reader.read_flat() pixelwidth = int(argv[1]) pixelheight = int(argv[2]) tskymapstart = MPI.Wtime() telepixels = np.zeros((pixelwidth*pixelheight*3),dtype=np.uint8) colorpixels = np.zeros((pixelwidth*pixelheight),dtype=np.uint8) skystartall = np.zeros((pixelwidth*pixelheight),dtype=np.uint32) telestartall = np.zeros((pixelwidth*pixelheight),dtype=np.uint32) colorall = np.zeros((pixelwidth*pixelheight),dtype=np.uint8) totnstepsall=np.zeros((wsize),dtype=np.uint32) tskymapend = MPI.Wtime() tskymap = tskymapend-tskymapstart tmin = 1.e6 tpercparmin=1.e6 hinit=1.e-1 #h=1.e-4 Router = 1000. Rplane = 700. Rs = 2. every = 1 deltalamb = 1.e-1 imagewidth = 50; imageheight = 50; tiny = 1.e-30 epsilon=1.e-8 eccentricity = 0.2 Rfac = 1.+1.e-10 heps = 1.e-14 semilatusr = 10.0 tstartpp=MPI.Wtime() #percent parallelized numperprocess = pixelheight*pixelwidth/wsize skystart=np.zeros((numperprocess),dtype=np.int32) telestart=np.zeros((numperprocess),dtype=np.int32) color = np.zeros((numperprocess),dtype=np.int8) totnsteps=np.zeros((numperprocess),dtype=np.int32) trk4all=np.zeros((numperprocess),dtype=np.float) ttelestop = MPI.Wtime() ttele = ttelestop-tstartpp trk4=float("inf") for index in range(numperprocess): ypix = int((id*numperprocess+index)/pixelwidth) xpix = (id*numperprocess+index)%pixelwidth tstartrk4=MPI.Wtime() totnsteps[index],skystart[index],telestart[index],color[index]=integrateNullGeodesic(xpix, ypix, pixelheight,pixelwidth, skypixelheight,skypixelwidth,imagewidth,imageheight,Rs,Router,Rplane,eccentricity, semilatusr, epsilon, tiny, hinit,Rfac,heps) tendrk4=MPI.Wtime() trk4=min(trk4,(tendrk4-tstartrk4)/float(totnsteps[index])) totnstepsmax=max(totnsteps) tstoppp = MPI.Wtime() tpercpar=tstoppp-tstartpp comm.Barrier() if id==0: totnstepsmaxall=0 else: totnstepsmaxall=None comm.Barrier() totnstepsmaxall=comm.reduce(totnstepsmax,op=MPI.MAX,root=0) tskymapall = comm.reduce(tskymap, op=MPI.MAX, root=0) tteleall = comm.reduce(ttele,op=MPI.MAX,root=0) comm.Gatherv(skystart,skystartall,root=0) comm.Gatherv(telestart, telestartall, root=0) comm.Gatherv(color,colorall, root=0) trk4min=comm.reduce(trk4,op=MPI.MIN,root=0) comm.Barrier() tend = MPI.Wtime() tall = tend-tstart if id==0: tindexstart = MPI.Wtime() for index in range(pixelheight*pixelwidth): if(colorall[index]==1): telepixels[telestartall[index]:telestartall[index]+3]=skypixels[skystartall[index]:skystartall[index]+3] else: telepixels[telestartall[index]]=255 #leave other two indices zero,red tindexend = MPI.Wtime() tindex = tindexend-tindexstart if id==0: twritestart = MPI.Wtime() ftele = open('teleview_{pw}_{ph}_{ws}.png'.format(pw=pixelwidth,ph=pixelheight,ws=wsize), "w") telewrite=Writer(width=pixelwidth,height=pixelheight,greyscale=False,alpha=False) telewrite.write_array(ftele,telepixels) ftele.close() twriteend=MPI.Wtime() twrite = twriteend-twritestart fsky.close() comm.Barrier() tmax = comm.reduce(tall,MPI.MAX,root=0) tpercparmin = comm.reduce(tpercpar/tall,op=MPI.MIN,root=0) comm.Barrier() if (id==0): # print("Telescope dimensions in M", 2.*imagewidth, 2.*imageheight) # print("Telescope resolution", pixelwidth, pixelheight) # print("Skymap resolution", skypixelwidth, skypixelheight) # print("Schwarzschild radius in M", 2.*Rs) # print("Outer radius in M", 2.*Router) # print("Telescope radius in M", 2.*Rplane) # print("Number of processes = ",wsize) # print("Maximum number of integration steps taken is",totnstepsmaxall) # print("The time for a single step of the RK4 is",trk4min) # print("Total runtime = ",tmax) # print("Fraction parallel = ", tpercparmin) print pixelwidth,pixelheight,wsize,totnstepsmaxall,trk4min,tmax,tpercparmin, tindex, twrite, tskymapall, tteleall MPI.Finalize()
def getTexture(texture, texcache): if texture not in texcache: r = Reader(texture) rgb = list(r.asRGBA()[2]) texcache[texture] = rgb return texcache[texture]
from png import Reader FILENAME = "target_gradent.png" background = Actor("background") background.web_color = "#000000" with open(FILENAME, 'rb') as f: reader = Reader(file=f) file_data = reader.read() """ (686, 300, <map at 0x7f153a04aa20>, {'alpha': True, 'size': (686, 300), 'planes': 4, 'interlace': 0, 'bitdepth': 8, 'greyscale': False, 'background': (255, 255, 255)}) """ image_width, image_height = file_data[0], file_data[1] # take the three ranges (drop alpha) for the whole width #colors = [c[:3] for c in list(zip(*list(file_data[2])))[:image_width]] #colors = list(file_data[2]) raw = list(file_data[2])[0] colors = list(zip(raw[::4], raw[1::4], raw[2::4])) go_and_back_colors = colors + colors[::-1]