2017-02-25 150 views
1

在我編寫的pygame應用程序中,我使用Surface.set_at()和get_at()方法直接處理像素。這不是時間敏感的,所以沒有問題。但是我看到一些奇怪的行爲。在被要求集合一個mcve之後,我確定了出現問題的具體情況。我的代碼:在pygame中使用set_at時,像素RGB值反轉

import pygame 

def is_color(surface,position,color): 
    col=surface.get_at(position) 
    return (col.r,col.g,col.b)==color 
def flood_fill(surface, position, fill_color): 
    frontier = [position] 
    fill=pygame.Color(fill_color[0],fill_color[1],fill_color[2],255) 
    n=0 
    while len(frontier) > 0 and n<50000: 
     x, y = frontier.pop() 
     try: 
      col=surface.get_at((x,y)) 
      if is_color(surface,(x,y),fill_color): 
       continue 
     except IndexError: 
      continue 
     surface.set_at((x,y),fill) 
     n+=1 
     frontier.append((x + 1, y)) 
     frontier.append((x - 1, y)) 
     frontier.append((x, y + 1)) 
     frontier.append((x, y - 1)) 

ROOD = (150,0,0) 
pygame.init() 
screen=pygame.display.set_mode((200,200)) 
colors=pygame.Surface((200,200)) 
pygame.draw.circle(colors,ROOD,(50,50),20,2) 
pygame.draw.circle(colors,ROOD,(150,150),20,2) 
flood_fill(colors,(50,50),ROOD) 
pygame.image.save(colors,"circles.png") 
del colors 
colors=pygame.image.load("circles.png") 
flood_fill(colors,(150,150),ROOD) 
screen.blit(colors,(0,0)) 
pygame.display.flip() 

當我按原樣運行(Windows 10)時,第一個圓圈被填滿,第二個填充操作失敗。問題似乎是從PNG文件讀取:當我將文件名更改爲circles.bmp時,沒有問題。所以我現在有一個解決方法。這是PNG文件處理中的錯誤,還是我錯過了這些東西應該如何工作的微妙之處?

+0

這不足以診斷問題。我們再次需要[mcve](http://stackoverflow.com/help/mcve)。 – skrx

+0

謝謝 - 我更新了我的問題,並在開發mcve時獲得了很多洞察。 – plantrob

回答

0

我不確定發生了什麼,但是您可以通過converting解決加載.png文件後表面的問題(通常應該總是轉換(或convert_alpha)新加載的圖像)。

colors = pygame.image.load("circles.png").convert() 
+0

謝謝 - 這就像一個魅力。 – plantrob