如何检测图像阈值内的颜色

时间:2020-11-06 02:37:51

标签: python pandas python-imaging-library

我正在一个项目中检测相同颜色范围的对象,我设法上载图像并获得编号。颜色,但它遍历每个像素,因此对于仅是2种颜色的图像(通过视力),输出获得太多颜色。我已经过滤了结果,只覆盖了覆盖1%以上的颜色。我尝试增加此范围,但消除了所用的主要颜色。

我知道产生这种结果的原因是由于图像的质量和每个图像的颜色。

我的问题是有什么方法可以调整阈值以提高结果,从而使其接近于否。可以通过视力计数的颜色。

from PIL import Image
from collections import Counter
import pandas as pd

img = Image.open("trial.JPG")
size = w, h = img.size
data = img.load()

colors = []
for x in range(w):
    for y in range(h):
        color = data[x, y]
        hex_color_lower = ''.join([hex(c)[2:].rjust(2, '0') for c in color])
        hex_color = hex_color_lower.upper()
        colors.append(hex_color)

total = w * h

color_hex = []
color_count = []
color_percent = []

df = pd.DataFrame()
for color, count in Counter(colors).items():
    percent = count/total * \
        100 
    if percent > 1:
        color_hex.append(color)
        color_count.append(count)
        color_percent.append(percent)

print(color_hex)

例如,此图像显示5种颜色,尽管只有2种颜色是灰色和白色。 ['FFFFFF','FCFCFC','FDFDFD','FEFEFE','FBFBFB']

enter image description here

1 个答案:

答案 0 :(得分:0)

您可以像这里这样计算颜色之间的相似度(stackoverflow.com/questions/5392061/…),只需将两种相似的颜色视为一种主要颜色。您可以尝试相似性阈值。

由于我不知道您的代码的输出格式,所以我不确定该代码是否会工作,但是基本逻辑会像这样

import numpy as np
from itertools import combinations


def img_distance(img1, img2):
    img1 = img1.convert('YCbCr')
    img2 = img2.convert('YCbCr')
    dist = np.linalg.norm(np.array(img1)-np.array(img2))
    return dist

combi_color = combinations(color_hex, 2)

for comb in combi_color:
    if img_distance(comb[0], comb[1]) < threshold:
       # Some operation that treats two colors as one
相关问题