I am trying to read frames from video but the video is useless after extracting frames. So I decide to use TempFile module. However the frame I use cv2.VideoCapture(NamedTempFile.name)
to get is always black. I am wondering if this is the right way to do it. if not, is there a better way? I attach the video capture part of my code below.
Also I doubt that the get_temp_video function might be wrong.
def get_temp_video(url, temp_file):
r = requests.get(url, stream=True)
for chunk in r.iter_content(chunk_size=1024):
if chunk:
temp_file.write(chunk)
return temp_file
def get_frame(video_url):
named_temp_file = NamedTemporaryFile()
named_temp_file = get_temp_video(video_url, named_temp_file)
named_temp_file.seek(0)
video = cv2.VideoCapture(named_temp_file.name)
while video.isOpened():
ret, frame = video.read()
if ret:
temp_file = TemporaryFile()
np.save(temp_file, frame)
temp_file.seek(0)
upload_to_some_where(temp_file.read())
temp_file.close()
else:
break
video.release()
named_temp_file.close()
I am guessing the problem is with your function upload_to_some_where
, because the rest of the code works fine for me. For testing purposes I slightly modified your code:
def get_temp_video(url, temp_file):
r = requests.get(url, stream=True)
for chunk in r.iter_content(chunk_size=1024):
if chunk:
temp_file.write(chunk)
return temp_file
def get_frame(video_url):
named_temp_file = NamedTemporaryFile()
named_temp_file = get_temp_video(video_url, named_temp_file)
named_temp_file.seek(0)
video = cv2.VideoCapture(named_temp_file.name)
while video.isOpened():
ret, frame = video.read()
if ret:
# For testing purpose
cv2.imshow("frame", frame)
if cv2.waitKey(25) == ord('q'):
break
##############################
# temp_file = TemporaryFile()
# np.save(temp_file, frame)
# temp_file.seek(0)
# upload_to_some_where(temp_file.read())
# temp_file.close()
else:
break
video.release()
named_temp_file.close()
if __name__=='__main__':
get_frame('http://samples.mplayerhq.hu/MPEG-4/MPEG4%20by%20philips.mp4')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.