Python 2.7 Python-计算唯一元素的频率

Python 2.7 Python-计算唯一元素的频率,python-2.7,dictionary,python-imaging-library,pillow,Python 2.7,Dictionary,Python Imaging Library,Pillow,我在字典中的键中有一组独特的RGB颜色:'Color'和目标图像中每个RGB颜色的列表 我想: 迭代目标RGB颜色列表 检查该元素是否与键中的任何颜色匹配:'Color' 如果匹配,我想更改键:频率将其增加1(+=1) 最后我希望实现更新frequency['frequency'],因此在过程结束时dict:frequency将包含一组(颜色、频率)。然后我想从较低的频率到较高的频率排序,并打印每对RGB颜色+外观数量 以下是我目前的代码: from PIL import Image im

我在字典中的
键中有一组独特的RGB颜色:'Color'
和目标图像中每个RGB颜色的
列表

我想:

  • 迭代目标RGB颜色列表
  • 检查该元素是否与
    键中的任何颜色匹配:'Color'
  • 如果匹配,我想更改
    键:频率
    将其增加1(+=1)
最后我希望实现更新
frequency['frequency']
,因此在过程结束时
dict:frequency
将包含一组
(颜色、频率)
。然后我想从较低的频率到较高的频率排序,并打印每对RGB颜色+外观数量

以下是我目前的代码:

from PIL import Image

im = Image.open('test.png').convert('RGB')
im2 = Image.open('test2.png').convert('RGB')

unique_colors = set()

def get_unique_colors(img):
    for i in range(0,img.size[0]):
        for j in range(0,img.size[1]):
            r,g,b = img.getpixel((i,j))
            unique_colors.add((r,g,b))
    return(unique_colors)

unique_colors = get_unique_colors(im)

all_colors = []

def get_all_colors(img):
    for i in range(0,img.size[0]):
        for j in range(0,img.size[1]):
            r,g,b = rgb_im.getpixel((i,j))
            all_colors.append((r,g,b))
    return(all_colors)

all_colors = get_all_colors(im2)

frequency = {'Color': list(unique_colors), 'Frequency': [0 for x in range(0,len(unique_colors))]}

我面临许多问题,因为我缺乏操作词典的能力。在这种情况下,使用词典来存储此类数据真的合适吗?

我认为您创建的词典是错误的。如果您创建的
dict
如下所示,则可以具有dict(颜色、频率)结构:

frequency = dict(zip(list(unique_colors), [0 for x in range(0,len(unique_colors))]))
zip
函数将两个列表作为键和值对放在一起。如果
unique_colors={'red'、'green'、'blue'}
,这将创建一个字典,如:

frequency = {'red': 0, 'green': 0, 'blue': 0}
之后,您可以将字典更新为:

frequency['red']+=1

然后dict变成
{'red':1,'green':0,'blue':0}

我认为您创建的字典不正确。如果您创建的
dict
如下所示,则可以具有dict(颜色、频率)结构:

frequency = dict(zip(list(unique_colors), [0 for x in range(0,len(unique_colors))]))
zip
函数将两个列表作为键和值对放在一起。如果
unique_colors={'red'、'green'、'blue'}
,这将创建一个字典,如:

frequency = {'red': 0, 'green': 0, 'blue': 0}
之后,您可以将字典更新为:

frequency['red']+=1

dict变成了
{'red':1,'green':0,'blue':0}

使用字典是一个好主意,事实证明标准库为您完成了
集合的一些工作。计数器计算您放入其中的内容。添加
itertools.product
以运行所有像素位置,并将其放入自定义像素迭代器中,您将获得

from PIL import Image
import collections
import itertools

def iter_colors(img):
    coordinates = itertools.product(range(img.size[0]), range(img.size[1]))
    return map(img.getpixel, coordinates)

im = Image.open('test.png').convert('RGB')
im2 = Image.open('test2.png').convert('RGB')

unique_colors = set(iter_colors(im))
print("unique", unique_colors)

frequencies = collections.Counter((rgb for rgb in iter_colors(im2)
    if rgb in unique_colors))
print("frequencies", frequencies)

# counter keys are rgb tuples and velue is number of times seen
rgbs_sorted = list(sorted(frequencies))
print("im2 rgb values sorted by value:", ", ".join(
    str(rgb) for rgb in rgbs_sorted))
print("im2 rgb values sorted by most common:", ", ".join(
    str(rgb) for rgb in frequencies.most_common()))
print("one rgb value", frequencies[rgbs_sorted[0]])
在测试映像上,返回

unique {(0, 0, 255), (191, 191, 191), (0, 255, 0)}
frequencies Counter({(191, 191, 191): 45, (0, 0, 255): 44, (0, 255, 0): 32})
im2 rgb values sorted by value: (0, 0, 255), (0, 255, 0), (191, 191, 191)
im2 rgb values sorted by most common: ((191, 191, 191), 45), ((0, 0, 255), 44), ((0, 255, 0), 32)
one rgb value 44

使用字典是一个很好的主意,事实证明标准库已经为您完成了
集合的一些工作。计数器
计算您放入其中的内容。添加
itertools.product
以运行所有像素位置,并将其放入自定义像素迭代器中,您将获得

from PIL import Image
import collections
import itertools

def iter_colors(img):
    coordinates = itertools.product(range(img.size[0]), range(img.size[1]))
    return map(img.getpixel, coordinates)

im = Image.open('test.png').convert('RGB')
im2 = Image.open('test2.png').convert('RGB')

unique_colors = set(iter_colors(im))
print("unique", unique_colors)

frequencies = collections.Counter((rgb for rgb in iter_colors(im2)
    if rgb in unique_colors))
print("frequencies", frequencies)

# counter keys are rgb tuples and velue is number of times seen
rgbs_sorted = list(sorted(frequencies))
print("im2 rgb values sorted by value:", ", ".join(
    str(rgb) for rgb in rgbs_sorted))
print("im2 rgb values sorted by most common:", ", ".join(
    str(rgb) for rgb in frequencies.most_common()))
print("one rgb value", frequencies[rgbs_sorted[0]])
在测试映像上,返回

unique {(0, 0, 255), (191, 191, 191), (0, 255, 0)}
frequencies Counter({(191, 191, 191): 45, (0, 0, 255): 44, (0, 255, 0): 32})
im2 rgb values sorted by value: (0, 0, 255), (0, 255, 0), (191, 191, 191)
im2 rgb values sorted by most common: ((191, 191, 191), 45), ((0, 0, 255), 44), ((0, 255, 0), 32)
one rgb value 44

感谢您的回复,非常简短的脚本,它的工作。唯一的问题是,我不确定如何从这个数据结构中检索特定的RGB颜色及其值。它们的工作原理与DICT非常相似(请参阅中的文档)。我已经添加了一些示例。感谢您的回复,非常简短的脚本,它很有效。唯一的问题是,我不确定如何从这个数据结构中检索特定的RGB颜色及其值。它们的工作原理与DICT非常相似(请参阅中的文档)。我添加了一些样品。谢谢,它帮助了很多。在那之后,我只需要做:
所有颜色中的e:I唯一颜色中的I:if e==I:frequency[e]+=1
,然后每个(R,G,B)元组都会更新其计数器。很高兴能够提供帮助!谢谢,这帮了大忙。在那之后,我只需要做:
所有颜色中的e:I唯一颜色中的I:if e==I:frequency[e]+=1
,然后每个(R,G,B)元组都会更新其计数器。很高兴能够提供帮助!