猿问

修复错误“切片”错误以在单独的 Excel 单元格中添加元素列表

我正在尝试获取要在 Excel 工作表中的单独单元格中列出的图像中的颜色列表以及计数和百分比

我已经设法将数据传输到 Excel 工作表,但它全部合并在一个单元格中。我已经搜索过如何做到这一点,但现在我得到了

TypeError: unhashable type: 'slice'

这是我尝试过的

import pandas as pd

from PIL import Image

from collections import Counter

import prettytable


img = Image.open("Original 2.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 = '#'+''.join([hex(c)[2:].rjust(2, '0') for c in color])

        colors.append(hex_color)


#pt = prettytable.PrettyTable(['Color', 'Count', 'Percentage'])


total = w * h


for color, count in Counter(colors).items():

    percent = int(count/total * 100)

    if percent > 0:

        #         pt.add_row([color, count, percent])


        # print(pt, total)


        final = {'colors': [colors],

                 'count': [count],

                 'percent': [percent]

                 }


        df = pd.DataFrame()

        df['colors'] = final[0::3]   <--------------Error returning from here

        df['count'] = final[1::3]

        df['percent'] = final[2::3]


        df.to_excel(r'C:\Users\Ahmed\Desktop\Project\export_dataframe.xlsx',

                    index=False, header=True)


慕无忌1623718
浏览 114回答 2
2回答

慕侠2389804

我决定使用列表而不是字典。我没有看到任何特别的优势。我还删除了两者int():percent&nbsp;=&nbsp;int(count/total&nbsp;*&nbsp;100)和if&nbsp;percent&nbsp;>&nbsp;0:因为如果您的图像具有多种色调,则该条件永远不会通过。完整代码如下:import pandas as pdfrom PIL import Imagefrom collections import Counterimg = Image.open("Original 2.JPG")size = w, h = img.sizedata = img.load()colors = []for x in range(w):&nbsp; &nbsp; for y in range(h):&nbsp; &nbsp; &nbsp; &nbsp; color = data[x, y]&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; hex_color = '#'+''.join([hex(c)[2:].rjust(2, '0') for c in color])&nbsp; &nbsp; &nbsp; &nbsp; colors.append(hex_color)total = w * hcolor_hex = []color_count = []color_percent =[]df = pd.DataFrame()for color, count in Counter(colors).items():&nbsp; &nbsp; percent = count/total * 100 # Do not make it int. Majority of colors are < 1%, unless you want >= 1%&nbsp; &nbsp; color_hex.append(color)&nbsp; &nbsp; color_count.append(count)&nbsp; &nbsp; color_percent.append(percent)df['color'] = color_hexdf['count'] = color_countdf['percent'] = color_percentdf.to_excel(r'C:\Users\Ahmed\Desktop\Project\export_dataframe.xlsx',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; index=False, header=True)

MYYA

for 循环中的代码确实没有意义。int对can return 的调用0将导致该 if 语句为 false。下面的所有内容(包括写入 Excel 文件)都会针对每种颜色执行。据推测,这是一个缩进错误。df['colors'] = final[0::3]&nbsp; &nbsp;<--------------Error returning from herefinal是一个dict. 您需要使用 3 个键之一来访问它。例如:final['colors'],它将返回像素颜色的整个列表,包括重复项。你想要的可以通过这段代码实现:import pandas as pdfrom PIL import Imagefrom collections import Counterimport prettytableimg = Image.open("Original 2.JPG")size = w, h = img.sizedata = img.load()colors = []for x in range(w):&nbsp; &nbsp; for y in range(h):&nbsp; &nbsp; &nbsp; &nbsp; color = data[x, y]&nbsp; &nbsp; &nbsp; &nbsp; hex_color = '#'+''.join([hex(c)[2:].rjust(2, '0') for c in color])&nbsp; &nbsp; &nbsp; &nbsp; colors.append(hex_color)#pt = prettytable.PrettyTable(['Color', 'Count', 'Percentage'])total = w * hcolors, counts = zip(*Counter(colors).items())percentages = tuple(count / total for count in counts)df = pd.DataFrame()df['colors'] = colorsdf['count'] = countsdf['percent'] = percentagesdf.to_excel(r'C:\Users\Ahmed\Desktop\Project\export_dataframe.xlsx',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; index=False, header=True)2 个关键行是:colors, counts = zip(*Counter(colors).items())percentages = tuple(count / total for count in counts)第一行创建了 2 个tuples具有所有独特颜色及其计数的颜色。元组基本上是不可变的list。zip与*解包运算符结合用于将键和值Counter(colors).items()对转换为它们自己的单独元组。第二行从生成器表达式创建一个元组,该元组为我们提供所有颜色的百分比。colors、counts、 和percentages全部对齐,因此相同的索引表示相同的颜色。
随时随地看视频慕课网APP

相关分类

Python
我要回答