10

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.

skrx
  • 19,980
  • 5
  • 34
  • 48
milkysheep
  • 101
  • 1
  • 1
  • 3

3 Answers3

12

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))
AdrienW
  • 3,092
  • 6
  • 29
  • 59
Matthijs
  • 439
  • 3
  • 16
  • I'm getting this error when I try to count the number of green pixels at this RGB scale (0,226,129): `TypeError: can only concatenate tuple (not "int") to tuple` – jpf5046 Jun 25 '19 at 16:51
3

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)
skrx
  • 19,980
  • 5
  • 34
  • 48
0xd3
  • 81
  • 4
3

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!

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395