How to compute colored pixel area on images using Python?

5.1k Views Asked by At
 import numpy as np
 from matplotlib import cm
 from matplotlib import pyplot as plt
 import Image
 from scipy import ndimage
 import Image, ImageDraw
 import PIL
 import cv
 import cv2
 from scipy.ndimage import measurements, morphology
 from PIL import Image
 from numpy import *
 from scipy.ndimage import filters
 import pylab

 img = np.asarray(Image.open('test.tif').convert('L')) #read and convert image
 img = 1 * (img < 127) # threshold

 plt.imshow(img, cmap=cm.Greys_r) # show as black and white
 plt.show()

Code above gives white pixels on black background, how to compute white region on image, then to split image into 100 rectangles and find rectangles with min, max and average numbers of pixels? thanks

1

There are 1 best solutions below

1
On

Since your image is binary you can just sum the values to get a count of the white pixels.

from PIL import Image
import numpy as np

img = np.asarray(Image.open("foo.jpg").convert('L'))
img = 1 * (img < 127)

m,n = img.shape

# use np.sum to count white pixels
print("{} white pixels, out of {} pixels in total.".format(img.sum(), m*n))

# use slicing to count any sub part, for example from rows 300-320 and columns 400-440
print("{} white pixels in rectangle.".format(img[300:320,400:440].sum()))

Use slicing to pick out any rectangle and use sum() on that part.