截图的过程图像 - Python

时间:2012-01-16 02:22:33

标签: python image colors

我正在尝试拍摄游戏的屏幕截图,宝石迷阵(8x8电路板),并从屏幕截图中提取电路板位置。我已经尝试过Image / Imagestat,自动复制,并从插槽中间抓取单个像素,但这些都没有用。所以我认为取8x8网格的每个方格的平均值会识别每一块 - 但是我无法使用Image / Imagestat和autopy这样做。

任何人都知道如何获取图像区域的像素或颜色值?或者更好的方法来识别具有主色的图像片段?

1 个答案:

答案 0 :(得分: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,并将其存储在数组'Rows'数组中。然后,我使用stats.mean为每个piecetype抓取平均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

利用这两个功能,可以刮擦屏幕,并将电路板状态转换为可以确定移动的阵列。如果这对任何人都有帮助,祝你好运,如果你对一个移动选择器进行微调,请告诉我。