将值字典与值列表进行比较

时间:2013-11-19 23:26:48

标签: python image python-imaging-library

我目前正在尝试将我从图像获取的像素R / G / B值列表与RGB值的预定义字典进行比较。我的问题是,将从图像中获取的每个RGB像素值与预定义字典值进行比较的最pythonic(和最简单)方法是什么。

更新

#!/usr/bin/python

import Image

img = Image.open("/home/user/Pictures/pic.jpg")
pix = img.load()

    width, height = img.size #Image size

    pixels = list(img.getdata())

       #used for testing 

picture_colours = {
        (1, 1, 1): 'known1',
        (4, 4, 4): 'known2',
        (7, 3, 0): 'known3',
        (8, 3, 0): 'known4',
        (9, 4, 0): 'known5',
        (10, 5, 1): 'known6',
        (11, 6, 2): 'known7',
        (12, 7, 3): 'known8',
        (13, 8, 4): 'known9',
        (12, 7, 3): 'known10'

}
colour_type = picture_colours.get(pixels, 'no match')
match = 0 #default value

for pixel in pixels:
        print pixel #used to ensure pixels are in the (x, x ,x) format
        colour_type = picture_colours.get(pixel, 'no match')
        print colour_type #printing either 'no match' or one of the dictionary names(w1,c,asian)
        if(colour_type != 'no match'):
                match = match + 1 #For every matched pixel, + 1

        if(match >= 30):
                print "\n\n\n\n The image matches the data in the corpus"
                break

2 个答案:

答案 0 :(得分:4)

看起来你的方法有点错误。尝试使用RGB值元组作为字典的键,并将结果的“名称”作为结果,然后查找像素:

colours = {
    (247, 217, 214): 'lc',
    (240, 186, 173): 'c'
}

colour_type = colours.get(pixel, 'no match')

只需确保pixel是RGB值的3项元组,上面应该可以正常工作。

答案 1 :(得分:1)

您可以将两个dict值与==进行比较,它会完全符合您的期望:

>>> {'r': 2, 'g': 3, 'b': 4} == {'g': 3, 'b': 4, 'r': 2}
True

因此,如果pixels是一个dicts列表列表,那么就这样做:

pixels[y][x] == lc

如果不是,只需编写一种将一种格式转换为另一种格式的函数:

def rgbify(rgbtuple):
    return {'r': rgbtuple[0], 'g': rgbtuple[1], 'b': rgbtuple[2]}
rgbify(pixels[y][x]) == lc

......或:

def rgbify(rgbdict):
    return (rgbdict['r'], rgbdict['g'], rgbdict['b'])
pixels[y][x] == rgbify(lc)

但这引发了一个问题,即为什么要首先使用不同的格式。你正在设计这两件事中的至少一件;为什么设计两种不兼容的格式?

如果您只想找到一种方法来使事情更明确,而不仅仅是三个数字的元组,您可能需要考虑这个:

>>> Color = collections.namedtuple('Color' list('rgb'))
>>> lc = Color(r=247, g=217, b=214)
Color(r=247, g=217, b=214)
>>> lc = Color(247, 217, 214)
>>> lc
Color(r=247, g=217, b=214)
>>> lc.r
247
>>> lc == (247, 217, 214)
True