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'])
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 test_greyscale(): qr = segno.make_qr('test') buff = io.BytesIO() qr.save(buff, kind='png', quiet_zone='white') buff.seek(0) reader = PNGReader(file=buff) reader.preamble() assert reader.greyscale
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_greyscale(): fn = _make_tmp_png_filename() res = cli.main(['--quiet-zone=white', '--output={0}'.format(fn), 'test']) with open(fn, 'rb') as f: data = io.BytesIO(f.read()) os.unlink(fn) assert 0 == res reader = PNGReader(file=data) reader.preamble() assert reader.greyscale
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 to_fits(self, out_file): """ Converts a PNG to file a FITS file. :param out_file: User specified filename for the FITS """ if not self.png: raise ValueError, "AstroPNG was not initialized with a PNG image" # Reading the PNG takes two passes (for now) r = Reader(self.png) width, height, imgdata, metadata = r.read() fluxes = numpy.vstack( itertools.imap(numpy.uint16, imgdata) ) r = Reader(self.png) chunks = r.chunks() has_fits = False has_quantization = False has_nans = False # Read the custom astro chunks while True: try: chunk_name, data = chunks.next() except: break if chunk_name == 'fITS': header = self.__read_fits_header(data) has_fits = True elif chunk_name == 'qANT': zzero, zscale = self.__read_quantization_parameters(data, height) has_quantization = True elif chunk_name == 'nANS': y_nans, x_nans = self.__read_nan_locations(data) has_nans = True elif chunk_name == 'iEND': break if has_quantization: random_numbers = self.__random_number_generator(N = width * height).reshape( (height, width) ) fluxes = (fluxes - random_numbers + 0.5) * numpy.vstack(zscale) + numpy.vstack(zzero) if has_nans: if y_nans.size > 0: fluxes[y_nans, x_nans] = numpy.nan fluxes = numpy.flipud(fluxes) hdu = pyfits.PrimaryHDU(fluxes, header) hdu.verify() hdu.writeto(out_file, output_verify='ignore')
def test_plte(): qr = segno.make_qr('test') buff = io.BytesIO() dark = (0, 0, 139) qr.save(buff, kind='png', dark=dark, light=None) buff.seek(0) reader = PNGReader(file=buff) reader.preamble() assert not reader.greyscale palette = reader.palette() assert 2 == len(palette) assert 0 == palette[0][3] # Transparent color dark_with_alpha = dark + (255, ) assert dark_with_alpha in palette
def test_plte_no_transparency(): qr = segno.make_qr('test') buff = io.BytesIO() dark = (0, 0, 139) light = (255, 255, 255) qr.save(buff, kind='png', dark=dark, light=light) buff.seek(0) reader = PNGReader(file=buff) reader.preamble() assert not reader.greyscale palette = reader.palette() assert 2 == len(palette) assert dark in palette assert light in palette
def test_not_greyscale(): qr = segno.make_qr('test') buff = io.BytesIO() qr.save(buff, kind='png', quiet_zone=None) # Three "colors": white, black, transparent buff.seek(0) reader = PNGReader(file=buff) reader.preamble() assert not reader.greyscale palette = reader.palette() assert 3 == len(palette) assert 0 == palette[0][3] # Transparent color assert (0, 0, 0, 255) in palette # black assert (255, 255, 255, 255) in palette # white
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 __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 test_not_greyscale(): fn = _make_tmp_png_filename() res = cli.main( ['--quiet-zone=transparent', '--output={0}'.format(fn), 'test']) with open(fn, 'rb') as f: data = io.BytesIO(f.read()) os.unlink(fn) assert 0 == res reader = PNGReader(file=data) reader.preamble() assert not reader.greyscale palette = reader.palette() assert 3 == len(palette) assert 0 == palette[0][3] # Transparent color assert (0, 0, 0, 255) in palette # black assert (255, 255, 255, 255) in palette # white
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 test_plte_colors(): fn = _make_tmp_png_filename() res = cli.main([ '--quiet-zone=green', '--finder-dark=purple', '--finder-light=yellow', '--output={0}'.format(fn), 'test' ]) with open(fn, 'rb') as f: data = io.BytesIO(f.read()) os.unlink(fn) assert 0 == res reader = PNGReader(file=data) reader.preamble() assert not reader.greyscale palette = reader.palette() assert 5 == len(palette) assert (0, 0, 0) in palette assert (255, 255, 255) in palette assert colors._color_to_rgb('green') in palette assert colors._color_to_rgb('purple') in palette assert colors._color_to_rgb('yellow') in palette
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 test_issue_54_notinverted(dark, light, transparent): qr = segno.make('The Beatles') assert 'M4-M' == qr.designator out = io.BytesIO() scale = 5 qr.save(out, kind='png', scale=scale, dark=dark, light=light) out.seek(0) reader = PNGReader(file=out) w, h, pixels, meta = reader.read() width, height = qr.symbol_size(scale=scale) assert width == w assert height == h assert meta['greyscale'] border_row = tuple([1] * w) expected_row = tuple([1] * 2 * scale + [0] * 7 * scale + [1]) for idx, row in enumerate(pixels): if idx < 10: assert border_row == tuple(row) elif idx == 10: assert expected_row == tuple(row)[:len(expected_row)] break assert transparent == reader.transparent
def test_plte_colors(): qr = segno.make_qr('test') buff = io.BytesIO() dark = (0, 0, 139) light = (255, 255, 255) qr.save(buff, kind='png', dark=dark, light=light, quiet_zone='green', finder_dark='purple', finder_light='yellow') buff.seek(0) reader = PNGReader(file=buff) reader.preamble() assert not reader.greyscale palette = reader.palette() assert 5 == len(palette) assert dark in palette assert light in palette assert colors._color_to_rgb('green') in palette assert colors._color_to_rgb('purple') in palette assert colors._color_to_rgb('yellow') in palette
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]
def getTexture(texture, texcache): if texture not in texcache: r = Reader(texture) rgb = list(r.asRGBA()[2]) texcache[texture] = rgb return texcache[texture]
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 to_liq(image: png.Reader, attr: liq.Attr) -> liq.Image: """ Convert png.Reader to liq.Image. """ width, height, data, info = image.read_flat() return attr.create_rgba(data, width, height, info.get('gamma', 0))