首页 > 解决方案 > 使用 OpenCv Python 的颜色预测系统

问题描述

在此处输入图像描述嗨,我是一名尝试制作颜色预测系统的初始开发人员,但我遇到了一些我无法理解的错误。我想你可以帮我解决这个问题....我会和你分享我的正确代码

这是错误:IndexError: index 1 is out of bounds for axis 0 with size 1

RGB2HEX(color): function 中显示的错误,但我无法解决它

这是代码:

def RGB2HEX(color):
return "#{:02x}{:02x}{:02x}".format(int(color[0]), int(color[1]), int(color[2]))

def get_image(image_path):
image = cv2.imread(image_path)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
return image

IMAGE_DIRECTORY = 'C:/Users/Dell/Desktop/CPS 02'
COLORS = {
    'GREEN': [0, 128, 0],
    'BLUE': [0, 0, 128],
    'YELLOW': [255, 255, 0]
}
images = []

for file in os.listdir(IMAGE_DIRECTORY):
    if not file.startswith('.'):
        images.append(get_image(os.path.join(IMAGE_DIRECTORY, file)))

# extracting colors from image 
def get_colors(images, number_of_colors, show_char = True):
for j in range(len(images)):
    modified_image = cv2.resize(images[j], (600, 400), interpolation = cv2.INTER_AREA)
    modified_image = modified_image.reshape(modified_image.shape[0]*modified_image.shape[1],1)

    clf = KMeans(n_clusters = number_of_colors)
    labels = clf.fit_predict(modified_image)

    counts = Counter(labels)

    center_colors = clf.cluster_centers_
    # We get ordered colors by iterating through the keys
    ordered_colors = [center_colors[i] for i in counts.keys()]
    hex_colors = [RGB2HEX(ordered_colors[i]) for i in counts.keys()]
    rgb_colors = [ordered_colors[i] for i in counts.keys()]

# matching an image by its color
def match_image_by_color(image, color, threshold = 60, number_of_colors = 10): 

image_colors = get_colors(image, number_of_colors, False)
selected_color = rgb2lab(np.uint8(np.asarray([[color]])))

select_image = False
for i in range(number_of_colors):
    curr_color = rgb2lab(np.uint8(np.asarray([[image_colors[i]]])))
    diff = deltaE_cie76(selected_color, curr_color)
    if (diff < threshold):
        select_image = True

return select_image

# Selecting an image
def show_selected_images(images, color, threshold, colors_to_match):
index = 1

for i in range(len(images)):
    selected = match_image_by_color(images[i], color, threshold, colors_to_match)
    if (selected):
        plt.subplot(1, 5, index)
        plt.imshow(images[i])
        index += 1

# printing the result 
plt.figure(figsize = (20, 10))
show_selected_images(images, COLORS['BLUE'], 60, 5)

标签: pythonopencvdata-scienceknn

解决方案


使用此页面作为导入等指南,我能够在我拥有的一些库存图像上成功实现您的代码并重新创建您的错误。我想我知道发生了什么。

我相信您正在阅读的图像是单通道(灰度),而不是 RGB。当你重塑图像时,你将每个图像变成一个 Nx1 向量——那里只有一个颜色通道。因此RGB2HEX(),当它引用一维图像矢量的第二维时,您的函数会出错。

当我改为读取三通道 (RGB) 图像并重塑为 Nx3 矩阵时,您的函数成功执行。我在下面包含了完整的代码。您会注意到可与灰度图像一起使用以重现错误的两行(已注释掉)。如果您想要灰度版本,显然注释掉 RGB 等效行。

from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import numpy as np
import cv2
from collections import Counter
import os
import argparse

def RGB2HEX(color):
    return "#{:02x}{:02x}{:02x}".format(int(color[0]), int(color[1]), int(color[2]))

def get_image(image_path):
    image = cv2.imread(image_path)
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    # example to read as grayscale image
    # image = cv2.imread(image_path, 0)
    return image

IMAGE_DIRECTORY = './path/to/images/'
COLORS = {
    'GREEN': [0, 128, 0],
    'BLUE': [0, 0, 128],
    'YELLOW': [255, 255, 0]
}
images = []

for file in os.listdir(IMAGE_DIRECTORY):
    if not file.startswith('.'):
        images.append(get_image(os.path.join(IMAGE_DIRECTORY, file)))

# extracting colors from image 
def get_colors(images, number_of_colors, show_char = True):
    for j in range(len(images)):
        modified_image = cv2.resize(images[j], (600, 400), interpolation = cv2.INTER_AREA)
        modified_image = modified_image.reshape(modified_image.shape[0]*modified_image.shape[1], 3)
        # example to use with grayscale images        
        # modified_image = modified_image.reshape(modified_image.shape[0]*modified_image.shape[1], 1)

        clf = KMeans(n_clusters = number_of_colors)
        labels = clf.fit_predict(modified_image)

        counts = Counter(labels)

        center_colors = clf.cluster_centers_
        # We get ordered colors by iterating through the keys
        ordered_colors = [center_colors[i] for i in counts.keys()]
        hex_colors = [RGB2HEX(ordered_colors[i]) for i in counts.keys()]
        rgb_colors = [ordered_colors[i] for i in counts.keys()]

推荐阅读