def read_png_or_jpeg2000(fobj, start_length, size): (start, length) = start_length fobj.seek(start) sig = fobj.read(12) if sig[:8] == b'\x89PNG\x0d\x0a\x1a\x0a': fobj.seek(start) im = PngImagePlugin.PngImageFile(fobj) return {"RGBA": im} elif sig[:4] == b'\xff\x4f\xff\x51' \ or sig[:4] == b'\x0d\x0a\x87\x0a' \ or sig == b'\x00\x00\x00\x0cjP \x0d\x0a\x87\x0a': if not enable_jpeg2k: raise ValueError( 'Unsupported icon subimage format (rebuild PIL with JPEG 2000 support to fix this)' ) # j2k, jpc or j2c fobj.seek(start) jp2kstream = fobj.read(length) f = io.BytesIO(jp2kstream) im = Jpeg2KImagePlugin.Jpeg2KImageFile(f) if im.mode != 'RGBA': im = im.convert('RGBA') return {"RGBA": im} else: raise ValueError('Unsupported icon subimage format')
def read_png_or_jpeg2000(fobj, start_length, size): (start, length) = start_length fobj.seek(start) sig = fobj.read(12) if sig[:8] == b"\x89PNG\x0d\x0a\x1a\x0a": fobj.seek(start) im = PngImagePlugin.PngImageFile(fobj) Image._decompression_bomb_check(im.size) return {"RGBA": im} elif ( sig[:4] == b"\xff\x4f\xff\x51" or sig[:4] == b"\x0d\x0a\x87\x0a" or sig == b"\x00\x00\x00\x0cjP \x0d\x0a\x87\x0a" ): if not enable_jpeg2k: raise ValueError( "Unsupported icon subimage format (rebuild PIL " "with JPEG 2000 support to fix this)" ) # j2k, jpc or j2c fobj.seek(start) jp2kstream = fobj.read(length) f = io.BytesIO(jp2kstream) im = Jpeg2KImagePlugin.Jpeg2KImageFile(f) Image._decompression_bomb_check(im.size) if im.mode != "RGBA": im = im.convert("RGBA") return {"RGBA": im} else: raise ValueError("Unsupported icon subimage format")
def level15(): my=Image.new('RGB',(100,100)) f=PngImagePlugin.PngImageFile(r'wire.png') for y in range(100): for x in range(100): my.putpixel((x,y), f.getpixel((y*100+x,0))) my.save(r'15.png','png')
def level_28(): im=PngImagePlugin.PngImageFile(r'bell.png') l=[] for y in range(im.size[1]): for x in range(im.size[0]): l.append(im.getpixel((x,y))[1]) print (l[:10]) paris=[(l[i],l[i+1]) for i in range(0,len(l),2)] # 根据"my paris" 将像素两两分为一组 # 可以看出基本上每个paris内两像素之差都为42 print (paris[:10]) diffs=[abs(i[0]-i[1]) for i in paris] # 计算两两像素之差的绝对值 print (diffs[:10]) d=[x for x in diffs if x!=42] # 过滤掉差值等于42的 print (d) s=''.join([chr(x) for x in d]) # 剩下的差值转为字符 print (s ) # 输出 whodunnit().split()[0] ? # 到此就有些让我奇怪了,whodunnit是到结尾才知道谋杀犯的侦探小说的意思,怎么会联想到Python发明人Guido Van Rossum ? # 难道是发音像 who done it 谁做了这些 print ('Guido Van Rossum'.split()[0] )
def getFiles(path): """ takes path in, opens all pngs in the dir and imports those into our input array returns size of matrix, the input matrices, the number of inputs and x, y dims """ x = y = None files = glob.glob(os.path.join(path, "*.png")) inputs = [] for f in files: print "Importing %s" % f img = PngImagePlugin.PngImageFile(file(f, "rb")) if not img: raise Exception("error parsing %s as png" % f) x, y = img.size inputs.append([None for a in range(x * y)]) for i in range(x): for j in range(y): pix = img.getpixel((i, j)) if pix == 0x00: val = 1 else: val = -1 inputs[-1][i * x + j] = val return (x * y, inputs, len(inputs), x, y)
def test_verify_not_ignores_crc_error_in_required_chunk(self): # check does not ignore crc errors in required chunks image_data = MAGIC + IHDR[:-1] + b"q" + TAIL ImageFile.LOAD_TRUNCATED_IMAGES = True try: with pytest.raises(SyntaxError): PngImagePlugin.PngImageFile(BytesIO(image_data)) finally: ImageFile.LOAD_TRUNCATED_IMAGES = False
def render_image(self, left_mm, top_mm, width_mm, height_mm, path): pil = PngImagePlugin.PngImageFile(fp=open(path)) ir = ImageReader(pil) try: self._canvas.drawImage(ir, left_mm * mm, top_mm * mm, width_mm * mm, height_mm * mm, mask='auto') except Exception as e: raise Exception("Cannot render image %s: %s" % (path, e))
def level_14(): # 先把wire.png的像素码成100*100 ## my=PIL.Image.new('RGB',(100,100)) ## f=PngImagePlugin.PngImageFile(ur'd:\wire.png') ## for y in xrange(100): ## for x in xrange(100): ## my.putpixel((x,y), f.getpixel((y*100+x,0))) ## my.save(ur'd:\14.png','png') ## 得到的图片里面有红色bit字样 ==> http://www.pythonchallenge.com/pc/return/bit.html # 提示 you took the wrong curve. # curve是曲线,这么说是要像蛋糕一样把像素盘起来? # 提示里面 100*100 = (100+99+99+98) + (... --> # 100*100 图像,从一边开始盘,100->99->99->98正好四条边盘完,再向内侧盘 # 98->97->97->96 找到规律 x->x-1->x-1->x-2 # 从左上角顺时针盘 my=Image.new('RGB',(100,100)) f=PngImagePlugin.PngImageFile(r'wire.png') print ('x,y=%d,%d'%(f.size[0],f.size[1])) n=100 # 每条边长度 x,y=0,0 i=0 #采用递增i,来放置pixel #螺旋状 while i<10000: #print( 'i,n=%d,%d'%(i,n)) # 上 for cnt in range(n): #在指定位置放置指定pixel my.putpixel((x+cnt,y),f.getpixel((i,0))) i+=1 x+=(n-1) # 右 for cnt in range(1,n): my.putpixel((x,y+cnt),f.getpixel((i,0))) i+=1 y+=(n-2) # 下 for cnt in range(1,n): my.putpixel((x-cnt,y),f.getpixel((i,0))) i+=1 x-=(n-2) # 左 for cnt in range(1,n-1): my.putpixel((x,y-cnt),f.getpixel((i,0))) i+=1 y-=(n-3) n-=2 # 调整要画的边长 my.save(r'14.png','png')
def showPath(self,l,showmark): """显示路径""" tm=[] # 用来保存从起点到终点的路径坐标列表 for i in l: tm.append((i.x,i.y)) if showmark: # 在新图中显示出路径来 f=PngImagePlugin.PngImageFile(r'maze.png') my=f.copy() draw=ImageDraw.Draw(my) draw.point(tm,showmark)# (0,0,255,255)) my.save(r'maze_showpath.png','png') # 将路径间隔着取像素的r值保存到zip文件中 f=PngImagePlugin.PngImageFile(r'maze.png') fo=open(r'maze_1.zip','wb') data=[] for i in tm[1::2]: # 从第二个像素开始间隔着取 r,dummy,dummy,dummy=f.getpixel(i) data.append(r) import array data = array.array("B", data).tostring() fo.write(data) fo.close()
def test_verify_ignores_crc_error(self): # check ignores crc errors in ancillary chunks chunk_data = chunk(b"tEXt", b"spam") broken_crc_chunk_data = chunk_data[:-1] + b"q" # break CRC image_data = HEAD + broken_crc_chunk_data + TAIL with pytest.raises(SyntaxError): PngImagePlugin.PngImageFile(BytesIO(image_data)) ImageFile.LOAD_TRUNCATED_IMAGES = True try: im = load(image_data) assert im is not None finally: ImageFile.LOAD_TRUNCATED_IMAGES = False
def png(datasets, export_method=None, template_data=None, concatenate=False): # NOTE: concatenate not supported for PNG - keyword ignored. from PIL import PngImagePlugin header_string = json_dumps(template_data) exports = [getattr(d, export_method)() for d in datasets] outputs = [] for i, export in exports: image = PngImagePlugin.PngImageFile(export["value"]) new_metadata = PngImagePlugin.PngInfo() existing_metadata = image.text for key, value in existing_metadata.items(): if isinstance(value, PngImagePlugin.iTXt): new_metadata.add_itxt(key, value) elif isinstance(value, str): new_metadata.add_text(key, value) new_metadata.add_itxt("reductus_template.json", header_string) value = io.BytesIO() image.save(value, pnginfo=new_metadata) filename = _build_filename(export, ext=".hdf5", index=i) outputs.append({"filename": filename, "value": value}) return outputs
class IconImporter(object): def __init__(self, feed, page_data=None, force=False): self.feed = feed self.force = force self.page_data = page_data self.feed_icon = MFeedIcon.get_feed(feed_id=self.feed.pk) def save(self): if not self.force and self.feed.favicon_not_found: # print 'Not found, skipping...' return if ( not self.force and not self.feed.favicon_not_found and self.feed_icon.icon_url and self.feed.s3_icon ): # print 'Found, but skipping...' return image, image_file, icon_url = self.fetch_image_from_page_data() if not image: image, image_file, icon_url = self.fetch_image_from_path(force=self.force) if image: image = self.normalize_image(image) try: color = self.determine_dominant_color_in_image(image) except IndexError: return try: image_str = self.string_from_image(image) except TypeError: return if len(image_str) > 500000: image = None if (image and (self.force or self.feed_icon.data != image_str or self.feed_icon.icon_url != icon_url or self.feed_icon.not_found or (settings.BACKED_BY_AWS.get('icons_on_s3') and not self.feed.s3_icon))): logging.debug(" ---> [%-30s] ~SN~FBIcon difference:~FY color:%s (%s/%s) data:%s url:%s notfound:%s no-s3:%s" % ( self.feed, self.feed_icon.color != color, self.feed_icon.color, color, self.feed_icon.data != image_str, self.feed_icon.icon_url != icon_url, self.feed_icon.not_found, settings.BACKED_BY_AWS.get('icons_on_s3') and not self.feed.s3_icon)) self.feed_icon.data = image_str self.feed_icon.icon_url = icon_url self.feed_icon.color = color self.feed_icon.not_found = False self.feed_icon.save() if settings.BACKED_BY_AWS.get('icons_on_s3'): self.save_to_s3(image_str) if self.feed.favicon_color != color: self.feed.favicon_color = color self.feed.favicon_not_found = False self.feed.save(update_fields=['favicon_color', 'favicon_not_found']) if not image: self.feed_icon.not_found = True self.feed_icon.save() self.feed.favicon_not_found = True self.feed.save() return not self.feed.favicon_not_found def save_to_s3(self, image_str): expires = datetime.datetime.now() + datetime.timedelta(days=60) expires = expires.strftime("%a, %d %b %Y %H:%M:%S GMT") k = Key(settings.S3_ICONS_BUCKET) k.key = self.feed.s3_icons_key k.set_metadata('Content-Type', 'image/png') k.set_metadata('Expires', expires) k.set_contents_from_string(image_str.decode('base64')) k.set_acl('public-read') self.feed.s3_icon = True self.feed.save() def load_icon(self, image_file, index=None): ''' DEPRECATED Load Windows ICO image. See http://en.wikipedia.org/w/index.php?oldid=264332061 for file format description. Cribbed and modified from http://djangosnippets.org/snippets/1287/ ''' try: image_file.seek(0) header = struct.unpack('<3H', image_file.read(6)) except Exception, e: return # Check magic if header[:2] != (0, 1): return # Collect icon directories directories = [] for i in xrange(header[2]): directory = list(struct.unpack('<4B2H2I', image_file.read(16))) for j in xrange(3): if not directory[j]: directory[j] = 256 directories.append(directory) if index is None: # Select best icon directory = max(directories, key=operator.itemgetter(slice(0, 3))) else: directory = directories[index] # Seek to the bitmap data image_file.seek(directory[7]) prefix = image_file.read(16) image_file.seek(-16, 1) if PngImagePlugin._accept(prefix): # Windows Vista icon with PNG inside try: image = PngImagePlugin.PngImageFile(image_file) except IOError: return else: # Load XOR bitmap try: image = BmpImagePlugin.DibImageFile(image_file) except IOError: return if image.mode == 'RGBA': # Windows XP 32-bit color depth icon without AND bitmap pass else: # Patch up the bitmap height image.size = image.size[0], image.size[1] >> 1 d, e, o, a = image.tile[0] image.tile[0] = d, (0, 0) + image.size, o, a # Calculate AND bitmap dimensions. See # http://en.wikipedia.org/w/index.php?oldid=264236948#Pixel_storage # for description offset = o + a[1] * image.size[1] stride = ((image.size[0] + 31) >> 5) << 2 size = stride * image.size[1] # Load AND bitmap image_file.seek(offset) string = image_file.read(size) mask = Image.frombytes('1', image.size, string, 'raw', ('1;I', stride, -1)) image = image.convert('RGBA') image.putalpha(mask) return image
def test_invalid_file(self): invalid_file = "Tests/images/flower.jpg" self.assertRaises(SyntaxError, lambda: PngImagePlugin.PngImageFile(invalid_file))
if index is None: # Select best icon directory = max(directories, key=operator.itemgetter(slice(0, 3))) else: directory = directories[index] # Seek to the bitmap data image_file.seek(directory[7]) prefix = image_file.read(16) image_file.seek(-16, 1) if PngImagePlugin._accept(prefix): # Windows Vista icon with PNG inside try: image = PngImagePlugin.PngImageFile(image_file) except IOError: return else: # Load XOR bitmap try: image = BmpImagePlugin.DibImageFile(image_file) except IOError: return if image.mode == 'RGBA': # Windows XP 32-bit color depth icon without AND bitmap pass else: # Patch up the bitmap height image.size = image.size[0], image.size[1] >> 1 d, e, o, a = image.tile[0]
def frame(self, idx): """ Get an image from frame idx """ header = self.entry[idx] self.buf.seek(header['offset']) data = self.buf.read(8) self.buf.seek(header['offset']) if data[:8] == PngImagePlugin._MAGIC: # png frame im = PngImagePlugin.PngImageFile(self.buf) else: # XOR + AND mask bmp frame im = BmpImagePlugin.DibImageFile(self.buf) # change tile dimension to only encompass XOR image im.size = (im.size[0], int(im.size[1] / 2)) d, e, o, a = im.tile[0] im.tile[0] = d, (0, 0) + im.size, o, a # figure out where AND mask image starts mode = a[0] bpp = 8 for k in BmpImagePlugin.BIT2MODE.keys(): if mode == BmpImagePlugin.BIT2MODE[k][1]: bpp = k break if 32 == bpp: # 32-bit color depth icon image allows semitransparent areas # PIL's DIB format ignores transparency bits, recover them. # The DIB is packed in BGRX byte order where X is the alpha # channel. # Back up to start of bmp data self.buf.seek(o) # extract every 4th byte (eg. 3,7,11,15,...) alpha_bytes = self.buf.read(im.size[0] * im.size[1] * 4)[3::4] # convert to an 8bpp grayscale image mask = Image.frombuffer( 'L', # 8bpp im.size, # (w, h) alpha_bytes, # source chars 'raw', # raw decoder ('L', 0, -1) # 8bpp inverted, unpadded, reversed ) else: # get AND image from end of bitmap w = im.size[0] if (w % 32) > 0: # bitmap row data is aligned to word boundaries w += 32 - (im.size[0] % 32) # the total mask data is # padded row size * height / bits per char and_mask_offset = o + int(im.size[0] * im.size[1] * (bpp / 8.0)) total_bytes = int((w * im.size[1]) / 8) self.buf.seek(and_mask_offset) mask_data = self.buf.read(total_bytes) # convert raw data to image mask = Image.frombuffer( '1', # 1 bpp im.size, # (w, h) mask_data, # source chars 'raw', # raw decoder ('1;I', int(w/8), -1) # 1bpp inverted, padded, reversed ) # now we have two images, im is XOR image and mask is AND image # apply mask image as alpha channel im = im.convert('RGBA') im.putalpha(mask) return im
def createWidgets(self): # fm1 self.fm1 = Frame(self, bg='black') self.titleLabel = Label(self.fm1, text="testing system", font=('微软雅黑', 64), fg="white", bg='black') self.titleLabel.pack() self.fm1.pack(side=TOP, expand=YES, fill='x', pady=20) # fm2 self.fm2 = Frame(self, bg='black') self.fm2_left = Frame(self.fm2, bg='black') self.fm2_right = Frame(self.fm2, bg='black') self.fm2_left_top = Frame(self.fm2_left, bg='black') self.fm2_left_bottom = Frame(self.fm2_left, bg='black') self.predictEntry = Entry(self.fm2_left_top, font=('微软雅黑', 24), width='72', fg='#FF4081') self.predictButton = Button(self.fm2_left_top, text='predict sentence', bg='#FF4081', fg='white', font=('微软雅黑', 36), width='16', command=self.output_predict_sentence) self.predictButton.pack(side=LEFT) self.predictEntry.pack(side=LEFT, fill='y', padx=20) self.fm2_left_top.pack(side=TOP, fill='x') self.truthEntry = Entry(self.fm2_left_bottom, font=('微软雅黑', 24), width='72', fg='#22C9C9') self.truthButton = Button(self.fm2_left_bottom, text='ground truth', bg='#22C9C9', fg='white', font=('微软雅黑', 36), width='16', command=self.output_ground_truth) self.truthButton.pack(side=LEFT) self.truthEntry.pack(side=LEFT, fill='y', padx=20) self.fm2_left_bottom.pack(side=TOP, pady=10, fill='x') self.fm2_left.pack(side=LEFT, padx=60, pady=20, expand=YES, fill='x') # self.nextVideoImg= ImageTk.PhotoImage(file = '/home/hl/Desktop/lovelyqian/nextVideo.png') self.nextVideoButton = Button(self.fm2_right, image='', text='next video', bg='black', command=self.start_play_video_thread) self.nextVideoButton.pack(expand=YES, fill=BOTH) self.fm2_right.pack(side=RIGHT, padx=60) self.fm2.pack(side=TOP, expand=YES, fill="x") # fm3 self.fm3 = Frame(self, bg='black') load = Image.open('/home/jun/Firefox_wallpaper.png') initIamge = PngImagePlugin.PngImageFile( file='/home/jun/Firefox_wallpaper.png') #ImageTk.PhotoImage(load) self.panel = Label(self.fm3, image=initIamge) self.panel.image = initIamge self.panel.pack() self.fm3.pack(side=TOP, expand=YES, fill=BOTH, pady=10)
def load_icon(_imgPath, index=None): if isinstance(_imgPath, basestring): file = open(_imgPath, 'rb') try: header = struct.unpack('<3H', file.read(6)) except: raise IOError('Not an ICO file') # Check magic try: if header[:2] != (0, 1): raise IOError('Not an ICO file') except: return loadPNG(_imgPath) # Collect icon directories directories = [] for i in xrange(header[2]): directory = list(struct.unpack('<4B2H2I', file.read(16))) for j in xrange(3): if not directory[j]: directory[j] = 256 directories.append(directory) if index is None: # Select best icon directory = max(directories, key=operator.itemgetter(slice(0, 3))) else: directory = directories[index] # Seek to the bitmap data file.seek(directory[7]) prefix = file.read(16) file.seek(-16, 1) if PngImagePlugin._accept(prefix): # Windows Vista icon with PNG inside image = PngImagePlugin.PngImageFile(file) else: # Load XOR bitmap image = BmpImagePlugin.DibImageFile(file) if image.mode == 'RGBA': # Windows XP 32-bit color depth icon without AND bitmap pass else: # Patch up the bitmap height image.size = image.size[0], image.size[1] >> 1 d, e, o, a = image.tile[0] image.tile[0] = d, (0, 0) + image.size, o, a # Calculate AND bitmap dimensions. See offset = o + a[1] * image.size[1] stride = ((image.size[0] + 31) >> 5) << 2 size = stride * image.size[1] # Load AND bitmap file.seek(offset) string = file.read(size) mask = Image.frombytes('1', image.size, string, 'raw', ('1;I', stride, -1)) image = image.convert('RGBA') image.putalpha(mask) return image, image.size
def load_icon(file, index=None): ''' Load Windows ICO image. See http://en.wikipedia.org/w/index.php?oldid=264332061 for file format description. ''' if isinstance(file, basestring): file = open(file, 'rb') header = struct.unpack('<3H', file.read(6)) # Check magic if header[:2] != (0, 1): raise SyntaxError('Not an ICO file') # Collect icon directories directories = [] for i in xrange(header[2]): directory = list(struct.unpack('<4B2H2I', file.read(16))) for j in xrange(3): if not directory[j]: directory[j] = 256 directories.append(directory) if index is None: # Select best icon directory = max(directories, key=operator.itemgetter(slice(0, 3))) else: directory = directories[index] # Seek to the bitmap data file.seek(directory[7]) prefix = file.read(16) file.seek(-16, 1) if PngImagePlugin._accept(prefix): # Windows Vista icon with PNG inside image = PngImagePlugin.PngImageFile(file) else: # Load XOR bitmap image = BmpImagePlugin.DibImageFile(file) if image.mode == 'RGBA': # Windows XP 32-bit color depth icon without AND bitmap pass else: # Patch up the bitmap height image.size = image.size[0], image.size[1] >> 1 d, e, o, a = image.tile[0] image.tile[0] = d, (0, 0) + image.size, o, a # Calculate AND bitmap dimensions. See # http://en.wikipedia.org/w/index.php?oldid=264236948#Pixel_storage # for description offset = o + a[1] * image.size[1] stride = ((image.size[0] + 31) >> 5) << 2 size = stride * image.size[1] # Load AND bitmap file.seek(offset) string = file.read(size) mask = Image.fromstring('1', image.size, string, 'raw', ('1;I', stride, -1)) image = image.convert('RGBA') image.putalpha(mask) return image
def test_invalid_file(self): invalid_file = "Tests/images/flower.jpg" with pytest.raises(SyntaxError): PngImagePlugin.PngImageFile(invalid_file)
def level_24(): class Node: def __init__(self,parent,x,y,h): self.parent=parent self.x,self.y=x,y self.hv = (x << 16) ^ y self.g,self.h=0,h def __repr__(self): return '(%d,%d)'%(self.x,self.y) def __eq__(self,other): return self.hv == other def __hash__(self): return self.hv class AStarTest: def __init__(self,map_max_x,map_max_y,map): self.openlist,self.closedlist=[],set() self.mapMaxX,self.mapMaxY=map_max_x,map_max_y print ('%d %d'%(self.mapMaxX,self.mapMaxY)) self.map=map def inCloseList(self,x,y): """检查(x,y)是否在closedlist中""" return (x << 16) ^ y in self.closedlist def inOpenList(self,x,y): """检查(x,y)是否在openlist中""" for i,n in enumerate(self.openlist): if n.x==x and n.y==y: return i return -1 def showPath(self,l,showmark): """显示路径""" tm=[] # 用来保存从起点到终点的路径坐标列表 for i in l: tm.append((i.x,i.y)) if showmark: # 在新图中显示出路径来 f=PngImagePlugin.PngImageFile(r'maze.png') my=f.copy() draw=ImageDraw.Draw(my) draw.point(tm,showmark)# (0,0,255,255)) my.save(r'maze_showpath.png','png') # 将路径间隔着取像素的r值保存到zip文件中 f=PngImagePlugin.PngImageFile(r'maze.png') fo=open(r'maze_1.zip','wb') data=[] for i in tm[1::2]: # 从第二个像素开始间隔着取 r,dummy,dummy,dummy=f.getpixel(i) data.append(r) import array data = array.array("B", data).tostring() fo.write(data) fo.close() def SubNode(self,node,to_x,to_y): """ 返回节点node的有效子节点""" subList=[(node.x,node.y-1),\ (node.x-1,node.y),\ (node.x+1,node.y),\ (node.x,node.y+1),] for x,y in subList: if self.map[y][x] !='#': # 坐标值有效 if not self.inCloseList(x,y): # 不在closedlist中 item= Node(node,x,y,math.sqrt((x-to_x)*(x-to_x)+(y-to_y)*(y-to_y))*1.2) item.g=item.parent.g+1.0 yield item def getPath(self,from_x,from_y,to_x,to_y,show_mark=None): """获取两点间的路径 from_coord 起点 to_coord 终点 show_mark 用来显示路径的颜色 """ print ("(%d,%d)->(%d,%d)"%(from_x,from_y,to_x,to_y)) self.openlist.append(Node(None,from_x,from_y,0)) while self.openlist: # 重复如下的工作: # a) 寻找开启列表中F值最低的格子。我们称它为当前格。 minf,minidx,curCoord=1000000,-1,None # 假设当前最新f为1000000 for i,n in enumerate(self.openlist): if n.g+n.h<minf: minf=n.g+n.h curCoord=n minidx=i # b) 把它切换到关闭列表。 del self.openlist[minidx] self.closedlist.add(curCoord) # c) 对相邻的8格中的每一个 for item in self.SubNode(curCoord,to_x,to_y): # 如果它不在开启列表中,把它添加进去。把当前格作为这一格的父节点。 # 记录这一格的F,G,和H值。 i=self.inOpenList(item.x,item.y) if i==-1: self.openlist.append(item) # 保存路径。从目标格开始,沿着每一格的父节点移动直到回到起始格。这就是你的路径。 if item.x==to_x and item.y==to_y: print ("found %d,len(closedlist)=%d"%(item.g,len(self.closedlist))) l=[item] p=item.parent while p: l.append(p) p=p.parent l.reverse() self.showPath(l,show_mark) return True # 如果它已经在开启列表中,用G值为参考检查新的路径是否更好。更低的G值 # 意味着更好的路径。如果是这样,就把这一格的父节点改成当前格,并且 # 重新计算这一格的G和F值。如果你保持你的开启列表按F值排序,改变之后 # 你可能需要重新对开启列表排序。 else: if item.g<self.openlist[i].g: self.openlist[i].parent=curCoord self.openlist[i].g=item.g print ("no path found!") return False # 准备地图数据 f=PngImagePlugin.PngImageFile(r'maze.png') # 将maze转为数组形式存入m m,line=[],[] for y in range(f.size[1]): for x in range(f.size[0]): if f.getpixel((x,y))==(255,255,255,255): line.append('#') # 白色为墙壁 else: line.append('.') # 其他为通路 m.append(''.join(line)) del line[:] # 调用A*算法找路 t=AStarTest(len(m[0]),len(m),m) t.getPath(639,0,1,640,(0,0,255,255))
def png_image(): return PngImagePlugin.PngImageFile(create_test_image('png'))
def load_icon(self, image_file, index=None): ''' DEPRECATED Load Windows ICO image. See http://en.wikipedia.org/w/index.php?oldid=264332061 for file format description. Cribbed and modified from http://djangosnippets.org/snippets/1287/ ''' try: image_file.seek(0) header = struct.unpack('<3H', image_file.read(6)) except Exception: return # Check magic if header[:2] != (0, 1): return # Collect icon directories directories = [] for i in range(header[2]): directory = list(struct.unpack('<4B2H2I', image_file.read(16))) for j in range(3): if not directory[j]: directory[j] = 256 directories.append(directory) if index is None: # Select best icon directory = max(directories, key=operator.itemgetter(slice(0, 3))) else: directory = directories[index] # Seek to the bitmap data image_file.seek(directory[7]) prefix = image_file.read(16) image_file.seek(-16, 1) if PngImagePlugin._accept(prefix): # Windows Vista icon with PNG inside try: image = PngImagePlugin.PngImageFile(image_file) except IOError: return else: # Load XOR bitmap try: image = BmpImagePlugin.DibImageFile(image_file) except IOError: return if image.mode == 'RGBA': # Windows XP 32-bit color depth icon without AND bitmap pass else: # Patch up the bitmap height image.size = image.size[0], image.size[1] >> 1 d, e, o, a = image.tile[0] image.tile[0] = d, (0, 0) + image.size, o, a # Calculate AND bitmap dimensions. See # http://en.wikipedia.org/w/index.php?oldid=264236948#Pixel_storage # for description offset = o + a[1] * image.size[1] stride = ((image.size[0] + 31) >> 5) << 2 size = stride * image.size[1] # Load AND bitmap image_file.seek(offset) string = image_file.read(size) mask = Image.frombytes('1', image.size, string, 'raw', ('1;I', stride, -1)) image = image.convert('RGBA') image.putalpha(mask) return image