The first thing that you need is a previous = cv2.blur(frame, (5,5))
to prime your previous sample after a frame grab before your while loop.
This will make the code you posted work, but will not solve your problem.
I think the issue that you are having is due to the type of thresholding algorithm that you are using. Try a binary, cv2.THRESH_BINARY
, instead of Otsu's. It seemed to solve the problem for me.