亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

修復錯誤“切片”錯誤以在單獨的 Excel 單元格中添加元素列表

修復錯誤“切片”錯誤以在單獨的 Excel 單元格中添加元素列表

慕無忌1623718 2024-01-27 15:03:37
我正在嘗試獲取要在 Excel 工作表中的單獨單元格中列出的圖像中的顏色列表以及計數和百分比我已經設法將數據傳輸到 Excel 工作表,但它全部合并在一個單元格中。我已經搜索過如何做到這一點,但現在我得到了TypeError: unhashable type: 'slice'這是我嘗試過的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):    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 * hfor 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)
查看完整描述

2 回答

?
慕俠2389804

TA貢獻1719條經驗 獲得超6個贊

我決定使用列表而不是字典。我沒有看到任何特別的優勢。我還刪除了兩者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)


查看完整回答
反對 回復 2024-01-27
?
MYYA

TA貢獻1868條經驗 獲得超4個贊

for 循環中的代碼確實沒有意義。

int對can return 的調用0將導致該 if 語句為 false。


下面的所有內容(包括寫入 Excel 文件)都會針對每種顏色執行。據推測,這是一個縮進錯誤。


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

final是一個dict. 您需要使用 3 個鍵之一來訪問它。例如:final['colors'],它將返回像素顏色的整個列表,包括重復項。


你想要的可以通過這段代碼實現:


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


colors, counts = zip(*Counter(colors).items())

percentages = tuple(count / total for count in counts)


df = pd.DataFrame()

df['colors'] = colors

df['count'] = counts

df['percent'] = percentages


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

            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全部對齊,因此相同的索引表示相同的顏色。


查看完整回答
反對 回復 2024-01-27
  • 2 回答
  • 0 關注
  • 180 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號