2012-01-16 23 views
1

我正在嘗試拍攝遊戲的截圖,珠光寶氣(8x8板),並從截圖中提取板的位置。我嘗試過Image/Imagestat,autopy,並從插槽中間抓取單個像素,但這些都沒有奏效。所以我在考慮以8x8網格的每個平方的平均值來識別每一個片段 - 但我一直無法使用Image/Imagestat和autopy來做到這一點。來自屏幕截圖的過程映像 - Python

任何人都知道一種方法來獲取圖像區域的像素或顏色值?或者更好的方式來識別具有主色的圖像片段?

回答

1

我已經找到了一種方法來使用Imagegrab和ImageStat與PIL做到這一點。下面是在屏幕和作物搶遊戲窗口:

def getScreen(): 
    # Grab image and crop it to the desired window. Find pixel borders manually. 
    box = (left, top, right, bottom)   
    im = ImageGrab.grab().crop(box) 
    #im.save('testcrop.jpg') # optionally save your crop 

    for y in reversed(range(8)): 
     for x in reversed(range(8)): 
      #sqh,sqw are the height and width of each piece. 
      #each pieceim is one of the game piece squares 
      piecebox = (sqw*(x), sqh*(y), sqw*(x+1), sqh*(y+1)) 
      pieceim = im.crop(piecebox) 
      #pieceim.save('piececrop_xy_'+ str(x) + str(y) + '.jpg') 

      stats = ImageStat.Stat(pieceim) 
      statsmean = stats.mean 
      Rows[x][y] = whichpiece(statsmean) 

上面針對所有64個產生圖像,識別piecetype,並且存儲陣列「行」的在數組中。然後,我用stats.mean爲每個片段類型抓取平均RGB值並將它們存儲在字典(rgbdict)中。將所有輸出複製到Excel中並按顏色類型過濾以獲得平均值。然後我使用RSS方法和字典來統計匹配圖像與已知的片段。 (RSS REF:http://www.charlesrcook.com/archive/2010/09/05/creating-a-bejeweled-blitz-bot-in-c.aspx

rgbdict = { 
      'blue':[65.48478993, 149.0030965, 179.4636593], #1 
      'red':[105.3613444,55.95710092, 36.07481793], #2 
      ...... 
      } 
def whichpiece(statsmean): 
     bestScore = 100 
     curScore= 0 
     pieceColor = 'empty' 
     for key in rgbdict.keys(): 
      curScore = (math.pow((statsmean[0]/255) - (rgbdict[key][0]/255), 2) 
       + math.pow((statsmean[1]/255) - (rgbdict[key][1]/255), 2) 
       + math.pow((statsmean[2]/255) - (rgbdict[key][2]/255), 2)) 
      if curScore < bestScore: 
       pieceColor = key 
       bestScore = curScore 
     return piececolor 

有了這兩個功能的屏幕可以刮下,並轉移到一個數組在其移動可以決定板的狀態。祝你好運,如果這有助於任何人,並讓我知道,如果你微調移動選擇器。