Reputation: 63
For example, I want to count and add the pixels between 100 and 255 from an image. I was thinking with two For.
rows,cols,bands=imgbgr.shape
for i in range(rows):
for j in range(cols):
for k in imgbgr[i,j]:
if 100<=k<=255:
#print imgbgr[i,j]
suma = np.sum(img[i,j])
print suma
Upvotes: 1
Views: 1443
Reputation: 5153
Since OpenCV returns numpy
arrays, you can use boolean slices to get the job done quicker:
>>> import numpy as np
>>> img = np.random.randint(0, 255, (3, 5, 5))
>>> img
array([[[236, 205, 246, 94, 224],
[ 28, 143, 159, 167, 54],
[247, 196, 107, 166, 74],
[194, 97, 219, 104, 15],
[143, 105, 107, 218, 240]],
[[ 54, 225, 231, 35, 39],
[223, 54, 0, 141, 47],
[ 69, 20, 222, 244, 143],
[ 34, 60, 174, 155, 243],
[173, 35, 173, 32, 246]],
[[229, 247, 102, 47, 208],
[201, 182, 172, 247, 171],
[ 86, 76, 182, 144, 58],
[155, 243, 37, 220, 75],
[171, 251, 60, 216, 43]]])
>>> cond = (img >= 100) & (img <= 255)
>>> cond
array([[[ True, True, True, False, True],
[False, True, True, True, False],
[ True, True, True, True, False],
[ True, False, True, True, False],
[ True, True, True, True, True]],
[[False, True, True, False, False],
[ True, False, False, True, False],
[False, False, True, True, True],
[False, False, True, True, True],
[ True, False, True, False, True]],
[[ True, True, True, False, True],
[ True, True, True, True, True],
[False, False, True, True, False],
[ True, True, False, True, False],
[ True, True, False, True, False]]], dtype=bool)
>>> img[cond]
array([236, 205, 246, 224, 143, 159, 167, 247, 196, 107, 166, 194, 219,
104, 143, 105, 107, 218, 240, 225, 231, 223, 141, 222, 244, 143,
174, 155, 243, 173, 173, 246, 229, 247, 102, 208, 201, 182, 172,
247, 171, 182, 144, 155, 243, 220, 171, 251, 216])
>>> img[cond].sum()
9360
Upvotes: 1