出现错误list indices must be integers or slices, not str

在对图像实现颜色聚类的时候,识别图像颜色,求取k均值距离最近的点时出现该问题:

原代码:

def closest_colour(requested_colour):
min_colors = {}
for key, name in color_dict['color_names'] .items() :
r_c, g_c, b_c = webcolors.hex_to_rgb( "#" + key)
rd = (r_c - requested_colour[0]) ** 2
gd = (g_c - requested_colour[1] ) ** 2
bd = (b_c - requested_colour[2] ) ** 2
min_colors[math.sqrt(rd + gd + bd)] = name
# print(min(min_colours.keys( ) ) )
return min_colors[min(min_colors.keys( ) ) ]

运行结果及报错内容

错误:
list indices must be integers or slices, not str

我在经过查询,该错误的意思是提示list的索引必须是整数或者片,而不是str,
完整的报错内容为:

 
Traceback (most recent call last):
  File "//Desktop-r2hqkul/共享/fengshuiling/julei/k-means2.py", line 184, in <module>
    main()
  File "//Desktop-r2hqkul/共享/fengshuiling/julei/k-means2.py", line 181, in main
    plotColorClusters(img)
  File "//Desktop-r2hqkul/共享/fengshuiling/julei/k-means2.py", line 150, in plotColorClusters
    cluster_map, kmeans = TrainKMeans(img)
  File "//Desktop-r2hqkul/共享/fengshuiling/julei/k-means2.py", line 49, in TrainKMeans
    h, name = findColorName(c)
  File "//Desktop-r2hqkul/共享/fengshuiling/julei/k-means2.py", line 98, in findColorName
    aname, cname = get_colour_name((int(rgb[0]), int(rgb[1]), int(rgb[2])))
  File "//Desktop-r2hqkul/共享/fengshuiling/julei/k-means2.py", line 134, in get_colour_name
    closest_name = closest_colour(requested_colour)
  File "//Desktop-r2hqkul/共享/fengshuiling/julei/k-means2.py", line 109, in closest_colour
    for key, name in color_dict['color_names'].items():
TypeError: list indices must be integers or slices, not str

109行出现问题,进行标点debug后发现是文件读取的问题,再读取color_dict时无法正确读到正确数据,重新检查文件,发现我使用的color_jsion颜色数据文件是从官网下载的,是没有经过处理的。重新找到下载该代码的github寻找jsion文件。发现原博主给的是已经将颜色信息转换为16进制的文件,再次处理运行,成功运行。

本次错误重点:在寻找错误时,需要学会正确灵活使用debug和断点的功能,非常好用,逐步输出结果查找错误。

posted @ 2022-05-20 09:32  heyrro  阅读(3270)  评论(0编辑  收藏  举报