python - 处理屏幕截图中的图像 - Python

标签 python image colors

我正在尝试截取 gem 迷阵游戏(8x8 棋盘)的屏幕截图,并从屏幕截图中提取棋盘位置。我尝试过 Image/Imagestat、尸检以及从插槽中间抓取单个像素,但这些都不起作用。因此,我认为取 8x8 网格的每个正方形的平均值可以识别每个部分 - 但我无法使用 Image/Imagestat 和 autopy 来做到这一点。

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

最佳答案

我找到了一种使用 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 个片段创建了一个图像,识别片段类型,并将其存储在数组“Rows”中。然后,我使用 stats.mean 获取每种工件类型的平均 RGB 值,并将它们存储在字典 (rgbdict) 中。将所有输出复制到 Excel 中并按颜色类型过滤以获得这些平均值。然后我使用 RSS 方法和该字典将图像与已知的片段类型进行统计匹配。 (RSS 引用: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

通过这两个函数,可以抓取屏幕,并将棋盘状态转移到一个数组中,根据该数组可以决定移动。如果这对任何人有帮助,祝你好运,如果你微调移动选择器,请告诉我。

关于python - 处理屏幕截图中的图像 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8875169/

相关文章:

android - 为什么Android无法识别颜色状态列表文件?

javascript - 如何根据当前时间更改 div 的颜色?

python - pandas - 列间条件的最佳行选择

python - MATLAB "any"条件删除翻译为 Python

python - 屏幕抓取图像(即 Firefox 页面信息/谷歌图像)

python - 如何在图像比例变大时围绕其中心旋转图像(在 Pygame 中)

python - tkinter 在 python 中渲染错误的 RGB 阴影

python - 用计算值替换 matplotlib 刻度标签的正确方法是什么?

python - 更清晰的代码来绕过在 Python 中打印 Int 值

android - 挂载 Android 模拟器镜像