You need to check your frame is empty or not after each query
Like
frame=cvQueryFrame(capture);
if (frame.empty()) break;
You are getting such an error because you are trying to convert an empty Mat to grayscale after last frame, so exit the loop if frame is empty.