How to count if circle (cv2.circle) cross the line (cv2.line)
I am able to create rectangles, circle(circle on a object) and a line, after that i want to count that if circle cross the line on a video. below is the example code:
while True:
ret, frame = cap.read()
imgray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
fgmask1 = cv2.GaussianBlur(imgray, (7,7), 0)
fgmask = fgbg.apply(fgmask1)
erode=cv2.erode(fgmask,None,iterations=3)
moments=cv2.moments(erode,True)
#area=moments['m00']
if point1 and point2:
cv2.line(frame, point1, point2, (0, 255, 0), 3)
contours, hierarchy = cv2.findContours(erode, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
try:
hierarchy = hierarchy[0]
except:
hierarchy = []
for contour, hier in zip(contours, hierarchy):
(x, y, w, h) = cv2.boundingRect(contour)
if w > 80 and h > 80:
cv2.rectangle(frame, (x,y), (x+w,y+h), (0, 255, 0), 2)
x1=w/2
y1=h/2
cx=x+x1
cy=y+y1
centroid = (cx,cy)
moments=cv2.moments(contour)
area=moments['m00']
if moments['m00'] >=minArea:
x=int(moments['m10']/moments['m00'])
y=int (moments['m01']/moments['m00'])
if x<lineCount:
sen=sen<<1
else:
sen=(sen<<1)|1
sen=sen&0x03
if sen==1:
counter=counter+1
cv2.circle(frame,(int(cx),int(cy)),1,(0,0,255),2)
cv2.line
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(frame,'counter='+str(counter), (10,30),font,1, (255, 0, 0), 2)
cv2.imshow("App", frame)
Point1 and point2 are mouse click callback. Is it possible to count if object cross the cv2.line. Or is there any solution other than that.
In case OpenCV doesn't offer a function for this, justt use basic trigonometric calculation to find out if distance from point to line is less than circle's radius
@manos. Does my answer is helped count if centroid. Just used my snippet code.
@mvuori and @supra56. I got this calculation (ax + by + c = 0) i am trying to merge with my code to solve this.. if you have any idea to merge to the code that please let me know.
I'm uncertainly about formula.
@mvuori and @supra56. I added a example image please find. and actually It need to be count if the red circle touch the green line every time on a video.
Now I understood. It is counting vehicles, stupid fool. Forgot your bloody formula. Now here is link that make you understand. people countingpeopel count 1counting vehicles What you trying to do is you must known x, y of lines crossing lines. The centroid cordinates is greater than crossing line. But not same same as rectangle. it is up to you. Studying people crossing. OK. Be nice.
Put the
centroid
in middle ofcv2.rectangle()
Forget about mouse click event.@supra56. I looked the examples of "1counting vehicles" that is good but i need to draw the line manually that where needed.
Just used
cv2.line
to draw horizontal line.@supra56. Please find my modified code. its not working.