Reputation: 922
I am trying to get the number of colours in a JPG file. I have followed a tutorial and created an white image with a black circle in it, so the number of colors in the image is 2 but from the code and the outcome is showing as just one color which is white.
How do I fix the code so that all the colors in the image is shown in the table outcome:
Here is the code:
from PIL import Image
from collections import Counter
import prettytable
img = Image.open("bnw.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'])
for color, count in Counter(colors).items():
pt.add_row([color, count])
print(pt)
Here is the outcome:
+---------+-------+
| Color | Count |
+---------+-------+
| #ffffff | 1000 |
+---------+-------+
Upvotes: 2
Views: 139
Reputation: 4251
You only call colors.append(hex_color)
for the last pixel in each x
. I think you meant this:
from PIL import Image
from collections import Counter
import prettytable
img = Image.open("bnw.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'])
for color, count in Counter(colors).items():
pt.add_row([color, count])
print(pt)
Upvotes: 3