Count total number of white pixels in an image

2024/11/15 9:44:31

I am trying to count total number of white pixels in the following image:

Image

But with my code, I get this error

src is not a numpy array, neither a scalar.

This is my code:

img=cv2.imread(filename,1)
TP= width * height
white= TP - cv2.countNonZero(img[1])
print "Dimensions:", img.size, "Total pixels:", TP, "White", white
Answer

Notice that Image is capitalized...in PIL, Image is a class. The actual image data is one of the many properties inside the class, and PIL does not use numpy arrays. Thus, your image is not a numpy array. If you want to convert to a numpy array, simply encase the image as an array:

img = np.array(img)

If you read the image with OpenCV, then it already comes as a numpy array.

img = cv2.imread(filename)

Also note that the ordering of channels is different in PIL than OpenCV. In PIL, images are read as RGB order, while in OpenCV, they are in BGR order. So if you read with PIL but display with OpenCV, you'll need to swap the channels before displaying.


Edit: also, check the OpenCV docs for countNonZero(). This function only works on single channel arrays, so you'll need to either convert the image to grayscale, or decide how you want to count a zero. You can also just use numpy just by np.sum(img == 0) to count the number of zero values, or np.sum(img > 0) to count non-zero values. For a three channel array, this will count all the zeros in each channel independently. If you want to only include ones that are zero in all three colors, you can do a number of things---the simplest is probably to add all the channels together into one 2D array, and then do the same as above.


Edit2: also, your code right now is counting the number of black pixels, not white. countNonZero() will return the number of all pixels greater than 0. Then you subtract that off the total number of pixels...which will give you only the black pixels. If you just want to count the number of white pixels, np.sum(img == 255).


Edit3: So with your image, this code works fine:

import cv2
import numpy as npimg = cv2.imread('img.png', cv2.IMREAD_GRAYSCALE)
n_white_pix = np.sum(img == 255)
print('Number of white pixels:', n_white_pix)

Number of white pixels: 5

Note here that cv2.IMREAD_GRAYSCALE is just equal to 0, but this is more explicit.

https://en.xdnf.cn/q/72265.html

Related Q&A

Pass a JSON object to an url with requests

So, I want to use Kenneth excellent requests module. Stumbled up this problem while trying to use the Freebase API.Basically, their API looks like that:https://www.googleapis.com/freebase/v1/mqlread?q…

jenkinsapi python - how to trigger and track the job result

I am using JenkinsAPI to trigger parametrized jobs. I am aware of the REST API that Jenkins use, but our setup does not allow that directly; so the main mean for me to trigger jobs is through this libr…

Django test parallel AppRegistryNotReady

I am trying to understand how to run django tests in parallel with in memory sqlite3.I have django app with that structure:gbookorder...tests__init__.pytest_a1.pytest_b1.pyutils.pytest_a1.py and test_b…

ImportError: PyCapsule_Import could not import module pyexpat

I am using Jenkins to build a python (Flask) solution to deploy to Google App Engine. As part of the build process I run a few integration tests. One of them is failing with the following error. ERROR:…

Python - Get max value in a list of dict

I have a dataset with this structure :In[17]: allIndices Out[17]: [{0: 0, 1: 1.4589, 4: 2.4879}, {0: 1.4589, 1: 0, 2: 2.1547}, {1: 2.1547, 2: 0, 3: 4.2114}, {2: 4.2114, 3: 0}, {0: 2.4879, 4: 0}]Id lik…

Rescaling axis in Matplotlib imshow under unique function call

I have written a function module that takes the argument of two variables. To plot, I hadx, y = pylab.ogrid[0.3:0.9:0.1, 0.:3.5:.5] z = np.zeros(shape=(np.shape(x)[0], np.shape(y)[1]))for i in range(le…

f2py array valued functions

Do recent versions of f2py support wrapping array-valued fortran functions? In some ancient documentation this wasnt supported. How about it now?Lets for example save the following function as func.f…

Unique strings in a pandas dataframe

I have following sample DataFrame d consisting of two columns col1 and col2. I would like to find the list of unique names for the whole DataFrame d. d = {col1:[Pat, Joseph, Tony, Hoffman, Miriam, Good…

finding index of multiple items in a list

I have a list myList = ["what is your name", "Hi, how are you","What about you", "How about a coffee", "How are you"]Now I want to search index of all …

Debugging asyncio code in PyCharm causes absolutely crazy unrepeatable errors

In my project that based on asyncio and asyncio tcp connections that debugs with PyCharm debugger I got very and very very absurd errors.If I put breakpoint on code after running, the breakpoint never …