嗨,我是一名初级开发人员,试图制作颜色预测系统,但我遇到了一些我无法理解的错误。我想你可以帮助我......我将与你分享我的正确代码
这是错误:IndexError:索引 1 超出尺寸 1 的轴 0 的范围
RGB2HEX(color): 函数中显示错误,但我无法解决它
这是代码:
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)
使用此page作为导入等指南,我能够在我拥有的一些库存图像上成功实现您的代码并重新创建您的错误。我想我知道发生了什么事。
我相信您正在阅读的图像是单通道(灰度),而不是 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()]