fixing the’slice’ error in the add list of elements in separate excel cells

The code within your for loop really doesn’t make sense.

This if statement is always true, which makes it redundant: if percent > 0: Edit: Ignore this. The call to int can return 0, which would cause this if statement to be false.

Everything below that, including writing to an excel file, is executed for every colour. Presumably this is an indentation error.

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

final is a dict. You need to access it using one of its 3 keys. For example: final['colors'], which would return the entire list of pixel colours, including duplicates.

What you want can be achieved with this code:

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)

The 2 key lines are:

colors, counts = zip(*Counter(colors).items())
percentages = tuple(count / total for count in counts)

The first line creates 2 tuples with all the unique colours and their counts. A tuple is basically an immutable list. zip combined with the * unpacking operator is used to transform the key and value pairs from Counter(colors).items() to their own separate tuples.

The second line creates a tuple from a generator expression which gives us the percentages of all the colours.

colors, counts, and percentages are all aligned so the same index refers to the same colour.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top