Reputation: 804
So basically I m trying to use OpenCV-Python to do motion detection. I used this tutorial to do so and here is my code.
import cv2
def diffImg(t0, t1, t2):
d1 = cv2.absdiff(t2, t1)
d2 = cv2.absdiff(t1, t0)
return cv2.bitwise_and(d1, d2)
cap = cv2.VideoCapture(0)
t = cv2.cvtColor(cap.read()[1], cv2.COLOR_BGR2GRAY)
tp = cv2.cvtColor(cap.read()[1], cv2.COLOR_BGR2GRAY)
tpp = cv2.cvtColor(cap.read()[1], cv2.COLOR_BGR2GRAY)
while cap.isOpened():
img = cv2.cvtColor(cap.read()[1], cv2.COLOR_BGR2GRAY)
img2 = diffImg(t,tp,tpp)
cv2.imshow("Motion", img2)
t=tp
tp=tpp
tpp=img
key = cv2.waitKey(10)
if key == 27 :
cv2.destroyAllWindows()
break
The I want to print on the console when there is a motion detection or not. When there is a motion, there are white pixels in the input image. But I don't know how to find white pixels in the input image. Can anyone tell me how to find if there are white pixels in the image returned by diffImg or not ?
Upvotes: 2
Views: 571
Reputation: 327
You could take a look to the countNonZero
function fom OpenCV.
Example provided by Baqir Khan:
if cv2.countNonZero(img2) > 29700:
print("Motion")
else:
print("No Motion")
Upvotes: 1