Ask Your Question
0

counting blue pixels in image python

asked 2013-11-01 11:06:44 -0600

memooo gravatar image

updated 2013-11-02 06:16:36 -0600

berak gravatar image

hello I am try to calculate blue pixels in image every time I run the code I got zero so anyone help me this is my code

    import cv2
import numpy as np

img = cv2.imread("mm.jpg")
BLUE_MIN = np.array([0, 0, 200], np.uint8)
BLUE_MAX = np.array([255, 50, 50], np.uint8)

dst = cv2.inRange(img, BLUE_MIN, BLUE_MAX)
no_blue = cv2.countNonZero(dst)
print('The number of blue pixels is: ' + str(no_blue))
cv2.namedWindow("opencv")
cv2.imshow("opencv",img)
cv2.waitKey(0)
edit retag flag offensive close merge delete

2 answers

Sort by ยป oldest newest most voted
0

answered 2013-11-02 12:20:28 -0600

Guanta gravatar image

Can't see right now why your way isn't working. For me it works:

Example:

>>> b
array([[[ 0,  1,  2]],
       [[ 3,  4,  5]],
       [[ 6,  7,  8]],
       [[ 9, 10, 11]]])

>>> c = cv2.inRange(b, np.array([3,4,5]), np.array([6,7,8]))
>>> c
array([[  0],
       [255],
       [255],
       [  0]], dtype=uint8)
>>> cv2.countNonZero(c)
2

another way would be to use more the numpy-functionality (probably there exist sth more elegant than this)

>>> np.count_nonzero((b[:,:,0] >= 3) & (b[:,:,1] >= 4) &\
   (b[:,:,2] >= 5) & (b[:,:,0] <= 6) & (b[:,:,1] <= 7) &\
   (b[:,:,2] <= 8))
2
edit flag offensive delete link more

Comments

Thanks for your help . However when i have ran this program the result is always zero i need to calculate the blue pixel in any image and if image does not has blue pixel then the result is zero

memooo gravatar imagememooo ( 2013-11-04 02:26:06 -0600 )edit
0

answered 2013-11-01 13:10:00 -0600

andr3w gravatar image

updated 2013-11-01 13:39:00 -0600

I do not know how things work in python, but in c++ you can do the following

cv::Mat bgrImage = cv::imread("test.jpg");
std::vector<cv::Mat> bgrChannels;

cv::split(bgrImage, bgrChannels);  // split multi-channels into single-channel
int blue = cv::countNonZero(bgrChannels[0]) // count the non-zero pixels on Blue channel

cv::split wrap for python cv2.split()

edit flag offensive delete link more

Question Tools

Stats

Asked: 2013-11-01 11:06:44 -0600

Seen: 12,241 times

Last updated: Nov 02 '13