繁体   English   中英

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

[英]Comparing a dictionary of values to a list of values

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

更新:

#!/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

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

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

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

只要确保pixel是RGB值的3个元素元组,上面的方法就可以了。

您可以将两个dict值与==进行比较,这将完全满足您的期望:

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

因此,如果pixels是字典列表的列表,请执行以下操作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM