Reputation: 118
I'm working with a little project with application of OpenCV
and I'm stuck with something that I don't know how to implement. Suppose I have an image (1024x768
). In this image there is a red bounding box at the center.
Is it possible to count the pixels inside the red box using OpenCS
? given that the image is 1024x768
in dimension.
I tried to use bounding rectangle by thresholding the red color and tried using convexhull
but then I can't extract how many pixels are inside the red marker.
Upvotes: 6
Views: 20346
Reputation: 1783
That's simple. Clearly the inner gray and outer colour are different. just threshold the image.
ret,thresh=cv2.threshold(img,133,255,cv2.THRESH_BINARY_INV)
Then use:
cv2.countNonZero(your_thresh_img)
That gives you the number of white pixels, which is the count you need. In your Image, it was 183920 pixels.
Edit
import numpy as np
import cv2
img=cv2.imread("your_image.png",0)
def nothing(x):
pass
cv2.namedWindow('image')
cv2.createTrackbar('min','image',0,255,nothing)
cv2.createTrackbar('max','image',0,255,nothing)
while(1):
a = cv2.getTrackbarPos('min','image')
b = cv2.getTrackbarPos('max','image')
ret,thresh=cv2.threshold(img,a,b,cv2.THRESH_BINARY_INV)
cv2.imshow("output",thresh)
k = cv2.waitKey(10) & 0xFF
if k == 27:
break
print cv2.countNonZero(thresh)
cv2.destroyAllWindows()
Upvotes: 12