簡體   English   中英

如何在 python 中檢測 png 中某些像素的 rgb 值?

[英]How do you detect the rgb value of some pixels from a png, in python?

我的代碼截取了屏幕截圖,(應該)測試屏幕截圖中的任何像素是否是通用 rgb 值(在我的示例中,它們的范圍為:r_min、r_max 和 g_min、g_max。此外,還有 end_time確保有足夠的時間掃描所有像素,因為它會截取另一張照片,並檢查另一張照片中的像素,直到找到特定像素,然后將變量 (fish_found) 的值從0 到 1,並通過 if 語句。

這是我想出的代碼:

    fish_found = 0
    im = screenshot('check.png')
    def find_fish(image_name):

        r_min = 140
        r_max = 190
        g_min = 85
        g_max = 185
        fish_found = 0
        img = Image.open(image_name)
        rgb = img.convert('RGB')
        for x in range(img.size[0]):
            for y in range(img.size[1]):
                r, g, b = rgb.getpixel((x, y))
                if r >= r_min and r <= r_max and g >= g_min and g <= g_max:
                    fish_found = fish_found + 1

    while True:
        im = screenshot('check.png', region=(990,415,20,20))
        end_time = datetime.now() + timedelta(seconds=0.5)
        while datetime.now() < end_time:
            find_fish('check.png')
        print(fish_found)
        if fish_found > 0:
            print("You found a fish")

好的,為任何需要它的人更新:整個代碼一團糟,我找到了一種更好的方法來確定像素是否匹配:

def function():
    pic = screenshot('screen.png', region=(985, 420, 30, 30))
    width, height = pic.size

    for x in range(0, width, 2):
        #modify the last digit to take greater steps, if you don't want to check every 
        #pixel
        for y in range(0, height, 2):
            #same thing, change the 2 to any value you want

            r, g, b = pic.getpixel((x, y))
            #this gets the actual rgb value of the pixel

            if r in range(250, 256) and g in range(195, 215) and b in range(28, 38):
                #put the range of values of r g b up here ^
                #down here you place your code (after you find out if they match, what do 
                #you do should be right here.
#after all of that, just call your function when you want to.
function()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM