Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count the number of pixels of a certain color in python?

Tags:

python

jes

I have a picture of two colours, black and red, and I need to be able to count how many pixels in the picture are red and how many are black.

like image 307
milkysheep Avatar asked Feb 18 '15 04:02

milkysheep


People also ask

How many pixels is my image Python?

Use PIL to load the image. The total number of pixels will be its width multiplied by its height. Save this answer.


3 Answers

I corrected code from 0xd3 to actually work:

from PIL import Image
im = Image.open('black.jpg')

black = 0
red = 0

for pixel in im.getdata():
    if pixel == (0, 0, 0): # if your image is RGB (if RGBA, (0, 0, 0, 255) or so
        black += 1
    else:
        red += 1
print('black=' + str(black)+', red='+str(red))
like image 154
Matthijs Avatar answered Oct 12 '22 00:10

Matthijs


According to http://personal.denison.edu/~bressoud/cs110-f12/Supplements/JESHelp/7_Picture_Functions.html , JES offers simple functions that do all you require, and something like

black = makeColor(0, 0, 0)
red = makeColor(255, 0, 0)
numblacks = numreds = 0
for pixel in getPixels(picture):
    color = getColor(pixel)
    if color == black: numblacks += 1
    elif color == red: numreds += 1

should easily do all you require (after whatever imports may be needed to make the functions available -- I don't have JES, nor have I ever seen or used it before; all I have is that doc which I found with a web search).

However, this seems so trivially easy that I guess there must be more to it -- I can't imagine anybody "stuck on this for three days" (!). But if as I suspect there's more, you have to be the one telling us -- what exactly is wrong with this code (plus whatever imports, def, return, or print, or whatever, your exact assignment requires) that appears to be using JES's functions to trivially solve the problem?! We can't help you unless you help us help you!

like image 36
Alex Martelli Avatar answered Oct 11 '22 23:10

Alex Martelli


First you need install pillow library.

sudo pip3 install pillow

from PIL import *
im = Image.open("your picture")

for pixel in im.getdata():
    if pixel is (0,0,0):
        black += 1
    else:
        red += 1
print("black = " + black + "red = " + red)
like image 25
0xd3 Avatar answered Oct 11 '22 23:10

0xd3