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.
Use PIL to load the image. The total number of pixels will be its width multiplied by its height. Save this answer.
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))
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!
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With