2 回答

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)

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