Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

285
Views
How to find the number of neighbours pixels in binary array

I am looking for an easy way to count the number of the green pixels in the image below, where the original image is the same but the green pixels are black.

I tried it with numpy.diff(), but then I am counting some pixels twice. I thought about numpy.gradient() – but here I am not sure if it is the right tool.

I know there have to be many solutions to this problem, but I don't know how to google for it. I am looking for a solution in python.

Image with a T

To make it clearer, I have only one image (only black and white pixels). The image with the green pixel is just for illustration.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You can use the edge detection kernel for this problem.

import numpy as np
from scipy.ndimage import convolve

a = np.array([[0, 0, 0, 0],
              [0, 1, 1, 1],
              [0, 1, 1, 1]])

kernel = np.array([[-1, -1, -1],
                   [-1,  8, -1],
                   [-1, -1, -1]])

Then, we will convolve the original array with the kernel. Notice that the edges are all negatives.

>>> convolve(a, kernel)
[[-1 -2 -3 -3]
 [-2  5  3  3]
 [-3  3  0  0]]

We will count the number of negative values and get the result.

>>> np.where(convolve(a, kernel) < 0, 1, 0)
[[1 1 1 1]
 [1 0 0 0]
 [1 0 0 0]]

>>> np.sum(np.where(convolve(a, kernel) < 0, 1, 0))
6

Edges-only kernel

There are a lot of things you can do with the kernel. For example, you can modify the kernel if you don't want to include diagonal neighbors.

kernel = np.array([[ 0, -1,  0],
                   [-1,  4, -1],
                   [ 0, -1,  0]])

This gives the following output.

>>> np.where(convolve(a, kernel) < 0, 1, 0)
[[0 1 1 1]
 [1 0 0 0]
 [1 0 0 0]]

>>> np.sum(np.where(convolve(a, kernel) < 0, 1, 0))
5
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!