计算不同的颜色像素-Python [英] Count different colour pixels - Python

查看:112
本文介绍了计算不同的颜色像素-Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里找到了此代码,但是它所做的只是计数黑色和红色,并且这仅适用于黑色和红色图像.

I found this code on here but all it does is count black and red, and this would only work with a black and red image.

from PIL import Image
im = Image.open('oh.png')

black = 0
red = 0

for pixel in im.getdata():
    if pixel == (0, 0, 0, 255): # if your image is RGB (if RGBA, (0, 0, 0, 255) or so
        black += 1
    else:
        red += 1
print('black=' + str(black)+', red='+str(red))

我如何能够检查不同的颜色而又没有那么精确,例如黑色可能是(0,0,0)到(40,40,40).

How would I be able to check different colours and not have it so precise, for example black could be (0, 0, 0) to (40,40,40).

这可能要问的太多了,只是让我知道. 谢谢:)

This may be too much to ask, just let me know. Thanks :)

推荐答案

这里是一种使用KDTree进行有效的最近颜色查找的方法.请注意,尽管KDTrees可能非常高级,但使用它们实际上非常简单.

Here is an approach using a KDTree for efficient nearest color lookup. Note that while KDTrees may be pretty advanced, using them is actually quite simple.

import numpy as np
from matplotlib import colors
from scipy.spatial import cKDTree as KDTree
from scipy.misc import face

REDUCED_COLOR_SPACE = True

# borrow a list of named colors from matplotlib
if REDUCED_COLOR_SPACE:
    use_colors = {k: colors.cnames[k] for k in ['red', 'green', 'blue', 'black', 'yellow', 'purple']}
else:
    use_colors = colors.cnames

# translate hexstring to RGB tuple
named_colors = {k: tuple(map(int, (v[1:3], v[3:5], v[5:7]), 3*(16,)))
                for k, v in use_colors.items()}
ncol = len(named_colors)

if REDUCED_COLOR_SPACE:
    ncol -= 1
    no_match = named_colors.pop('purple')
else:
    no_match = named_colors['purple']

# make an array containing the RGB values 
color_tuples = list(named_colors.values())
color_tuples.append(no_match)
color_tuples = np.array(color_tuples)

color_names = list(named_colors)
color_names.append('no match')

# get example picture
img = face()

# build tree
tree = KDTree(color_tuples[:-1])
# tolerance for color match `inf` means use best match no matter how
# bad it may be
tolerance = np.inf
# find closest color in tree for each pixel in picture
dist, idx = tree.query(img, distance_upper_bound=tolerance)
# count and reattach names
counts = dict(zip(color_names, np.bincount(idx.ravel(), None, ncol+1)))

print(counts)

import pylab

pylab.imshow(img)
pylab.savefig('orig.png')
pylab.clf()
pylab.imshow(color_tuples[idx])
pylab.savefig('minimal.png' if REDUCED_COLOR_SPACE else 'reduced.png')

具有名为color space的完整matplotlib的输出:

Output with full matplotlib named color space:

{'aliceblue':315,'antiquewhite':0,'aqua':0,'aquamarine':0,'azure':0,'beige':27,'bisque':0,'black': 88584,'blanchedalmond':0,'blue':0,'blueviolet':0,'brown':0,'burlywood':76,'cadetblue':0,'chartreuse':0,'chocolate':0, '珊瑚':0,'玉米花蓝色':0,'玉米丝':0,'深红色':0,'青色':0,'深蓝色':0,'深蓝色':0,'深金棒'':0,'达格雷':0,'darkgreen':4148,'darkgrey':71985,'darkkhaki':32907,'darkmagenta':0,'darkolivegreen':90899,'darkorange':0,'darkorchid':0,'darkred': 0,'darksalmon':0,'darkseagreen':30171,'darkslateblue':134,'darkslategray':108608,'darkslategrey':0,'darkturquoise':0,'darkviolet':0,'deeppink':0, 'deepskyblue':0,'dimgray':0,'dimgrey':108318,'dodgerblue':0,'firebrick':0,'floralwhite':0,'forestgreen':1,''紫红色':0,'gainsboro ':10438,'ghostwhite':736,'gold':0,'goldenrod':0,'gray':0,'green':0,'greenyellow':0,'grey':79835,'honeydew': 0,'hotpink':0,'indianred':0,'in digo':0,'ivory':0,'khaki':1056,'lavender':4650,'lavenderblush':46,'lawngreen':0,'lemonchiffon':0,'lightblue':3,'lightcoral' :0,'lightcyan':0,'lightgoldenrodyellow':0,'lightgray':11905,'lightgreen':2323,'lightgrey':0,'lightpink':0,'lightsalmon':0,'lightseagreen':0 ,'lightskyblue':0,'lightslategray':0,'lightslategrey':31920,'lightsteelblue':3590,'lightyellow':0,'lime':0,'limegreen':0,'linen':46,'洋红色':0,'栗色':0,'中等海蓝宝石':0,'中等蓝色':0,'中等兰花':0,'中等紫色':15,'中等海绿色':0,'中等深蓝色':0,'中等春天绿色' :0,中绿松石":0,中紫罗兰色":0,午夜蓝":54,薄荷奶油":0,迷雾玫瑰":19,鹿皮鞋":0,纳瓦霍怀特":0,海军":0 ,'oldlace':0,'olive':0,'olivedrab':30828,'orange':0,'orangered':0,'orchid':0,'palegoldenrod':1499,'palegreen':285,' paleturquoise':0,'palevioletred':0,'papayawhip':0,'peachpuff':0,'peru':21,'pink':0,'plum':0,'powde rblue':0,'purple':0,'rebeccapurple':0,'red':0,'rosybrown':2831,'royalblue':0,'saddlebrown':0,'salmon':0,'sandybrown' :0,'seagreen':0,'seashell':0,'sienna':5,'silver':35951,'skyblue':0,'slateblue':0,'slategray':7836,'slategrey':0 ,雪":18,春绿":0,钢蓝":0,棕褐色":3925,蓝绿色":0,蓟":10274,番茄":0,绿松石":0,紫色":0,小麦":21,白色":3,烟熏":834,黄色":0,黄色绿色":9292,不匹配":0}

{'aliceblue': 315, 'antiquewhite': 0, 'aqua': 0, 'aquamarine': 0, 'azure': 0, 'beige': 27, 'bisque': 0, 'black': 88584, 'blanchedalmond': 0, 'blue': 0, 'blueviolet': 0, 'brown': 0, 'burlywood': 76, 'cadetblue': 0, 'chartreuse': 0, 'chocolate': 0, 'coral': 0, 'cornflowerblue': 0, 'cornsilk': 0, 'crimson': 0, 'cyan': 0, 'darkblue': 0, 'darkcyan': 0, 'darkgoldenrod': 0, 'darkgray': 0, 'darkgreen': 4148, 'darkgrey': 71985, 'darkkhaki': 32907, 'darkmagenta': 0, 'darkolivegreen': 90899, 'darkorange': 0, 'darkorchid': 0, 'darkred': 0, 'darksalmon': 0, 'darkseagreen': 30171, 'darkslateblue': 134, 'darkslategray': 108608, 'darkslategrey': 0, 'darkturquoise': 0, 'darkviolet': 0, 'deeppink': 0, 'deepskyblue': 0, 'dimgray': 0, 'dimgrey': 108318, 'dodgerblue': 0, 'firebrick': 0, 'floralwhite': 0, 'forestgreen': 1, 'fuchsia': 0, 'gainsboro': 10438, 'ghostwhite': 736, 'gold': 0, 'goldenrod': 0, 'gray': 0, 'green': 0, 'greenyellow': 0, 'grey': 79835, 'honeydew': 0, 'hotpink': 0, 'indianred': 0, 'indigo': 0, 'ivory': 0, 'khaki': 1056, 'lavender': 4650, 'lavenderblush': 46, 'lawngreen': 0, 'lemonchiffon': 0, 'lightblue': 3, 'lightcoral': 0, 'lightcyan': 0, 'lightgoldenrodyellow': 0, 'lightgray': 11905, 'lightgreen': 2323, 'lightgrey': 0, 'lightpink': 0, 'lightsalmon': 0, 'lightseagreen': 0, 'lightskyblue': 0, 'lightslategray': 0, 'lightslategrey': 31920, 'lightsteelblue': 3590, 'lightyellow': 0, 'lime': 0, 'limegreen': 0, 'linen': 46, 'magenta': 0, 'maroon': 0, 'mediumaquamarine': 0, 'mediumblue': 0, 'mediumorchid': 0, 'mediumpurple': 15, 'mediumseagreen': 0, 'mediumslateblue': 0, 'mediumspringgreen': 0, 'mediumturquoise': 0, 'mediumvioletred': 0, 'midnightblue': 54, 'mintcream': 0, 'mistyrose': 19, 'moccasin': 0, 'navajowhite': 0, 'navy': 0, 'oldlace': 0, 'olive': 0, 'olivedrab': 30828, 'orange': 0, 'orangered': 0, 'orchid': 0, 'palegoldenrod': 1499, 'palegreen': 285, 'paleturquoise': 0, 'palevioletred': 0, 'papayawhip': 0, 'peachpuff': 0, 'peru': 21, 'pink': 0, 'plum': 0, 'powderblue': 0, 'purple': 0, 'rebeccapurple': 0, 'red': 0, 'rosybrown': 2831, 'royalblue': 0, 'saddlebrown': 0, 'salmon': 0, 'sandybrown': 0, 'seagreen': 0, 'seashell': 0, 'sienna': 5, 'silver': 35951, 'skyblue': 0, 'slateblue': 0, 'slategray': 7836, 'slategrey': 0, 'snow': 18, 'springgreen': 0, 'steelblue': 0, 'tan': 3925, 'teal': 0, 'thistle': 10274, 'tomato': 0, 'turquoise': 0, 'violet': 0, 'wheat': 21, 'white': 3, 'whitesmoke': 834, 'yellow': 0, 'yellowgreen': 9292, 'no match': 0}

仅输出基本颜色:

{'red':0,'green':403561,'blue':3262,'black':153782,'yellow':225827,'no match':0}

{'red': 0, 'green': 403561, 'blue': 3262, 'black': 153782, 'yellow': 225827, 'no match': 0}

原始图片:

减少颜色的版本:

基本颜色版本:

这篇关于计算不同的颜色像素-Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆