-1

I'm trying to calculate the sum of white pixels in multiple images.

I am able to count the number of white pixels in one image (2.png )with this code below:

import cv2
import numpy as np
image = cv2.imread('2.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
pixels = cv2.countNonZero(gray)
print('pixel count', pixels)

, but I don't know how to do it with multiple images. I would like to input multiple images and get the sum of all the white pixels. I'm fairly new to python and need some help with this. Thank you!

jennifer
  • 1
  • 1
  • Hello @jennifer, please provide an example of what you tried and a more specific question – Nicolò Gasparini Apr 12 '20 at 16:52
  • @NicolòGasparini Hello, thank you for the response. Sorry that my question wasn't more specific. I edited the question with images and code, and I hope it's clearer now. Thank you very much! – jennifer Apr 13 '20 at 17:37

1 Answers1

0

Since you already achieved the hard part (that was reading the number of white pixels, what you want to do is a simple iteration, since you have multiple images, that's the list of elements you will be iterating, something like this:

import cv2
import numpy as np
counter = 0
for img_path in ['2.png', '3.png', '4.png']:  # all of your images
    image = cv2.imread(img_path)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    pixels = cv2.countNonZero(gray)
    counter += pixels  # Keeping track ot the *total* number of pixels

print('total pixel count', counter)
Nicolò Gasparini
  • 2,228
  • 2
  • 24
  • 53
  • Thank you @Nicolò Gasparini ! I was wondering if I can read the images by a file path ex. D:\folder, since I have around 50~60 images to process. Very much appreciated! – jennifer Apr 14 '20 at 00:16
  • Yes you can, here you can find an answer: https://stackoverflow.com/questions/3207219/how-do-i-list-all-files-of-a-directory – Nicolò Gasparini Apr 14 '20 at 07:39