【问题标题】:Process image from screenshot - Python从屏幕截图处理图像 - Python
【发布时间】:2012-01-16 02:22:32
【问题描述】:

我正在尝试截取一个游戏的屏幕截图,使用宝石镶嵌(8x8 棋盘),然后从屏幕截图中提取棋盘位置。我已经尝试过 Image/Imagestat、autopy 和从插槽中间抓取单个像素,但这些都没有奏效。所以我想取 8x8 网格的每个正方形的平均值来识别每一块 - 但我无法使用 Image/Imagestat 和 autopy 这样做。

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

【问题讨论】:

    标签: python image colors


    【解决方案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 个片段创建了一个图像,识别片段类型,并将其存储在数组“行”的数组中。然后,我使用 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
    

    通过这两个功能,可以刮屏,并将棋盘状态转移到可以决定移动的数组中。如果这对任何人有帮助,祝你好运,如果你微调了移动选择器,请告诉我。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-20
      • 1970-01-01
      • 2010-11-14
      • 1970-01-01
      • 2017-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多