gpt4 book ai didi

python - 修复错误 'slice' 错误以在单独的 Excel 单元格中添加元素列表

转载 作者:行者123 更新时间:2023-12-04 21:46:16 25 4
gpt4 key购买 nike

我正在尝试将图像中的颜色列表与计数和百分比一起列在 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)

最佳答案

我决定使用列表而不是字典。我没有看到任何特别的优势。我还删除了两个删除 int()从:

percent = int(count/total * 100)
if percent > 0:
因为如果您的图像具有多种颜色,则条件将永远不会通过。
完整代码如下:
import pandas as pd
from PIL import Image
from collections import Counter

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)

total = w * h

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

df = pd.DataFrame()
for color, count in Counter(colors).items():
percent = count/total * 100 # Do not make it int. Majority of colors are < 1%, unless you want >= 1%
color_hex.append(color)
color_count.append(count)
color_percent.append(percent)

df['color'] = color_hex
df['count'] = color_count
df['percent'] = color_percent


df.to_excel(r'C:\Users\Ahmed\Desktop\Project\export_dataframe.xlsx',
index=False, header=True)

关于python - 修复错误 'slice' 错误以在单独的 Excel 单元格中添加元素列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64584735/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com