Skip to content

Instantly share code, notes, and snippets.

@leonidk
Last active June 6, 2016 05:15
Show Gist options
  • Save leonidk/291775abfe0f41580353 to your computer and use it in GitHub Desktop.
Save leonidk/291775abfe0f41580353 to your computer and use it in GitHub Desktop.
FFMPEG for Video Reading
import subprocess as sp
import numpy as np
import re
import cv2
FFMPEG_BIN = r'C:\Users\Leo\ffmpeg\bin\ffmpeg.exe'
INPUT_VID = 'Ecolipresentation.m4v'
def getInfo():
command = [FFMPEG_BIN,'-i', INPUT_VID, '-']
pipe = sp.Popen(command, stdout=sp.PIPE, stderr=sp.PIPE)
pipe.stdout.readline()
pipe.terminate()
infos = pipe.stderr.read()
infos_list = infos.split('\r\n')
res = re.search(' \d+x\d+ ',infos)
res = [int(x) for x in res.group(0).split('x')]
return res
res = getInfo()
command = [ FFMPEG_BIN,
'-i', INPUT_VID,
'-f', 'image2pipe',
'-pix_fmt', 'rgb24',
'-vcodec', 'rawvideo', '-']
pipe = sp.Popen(command, stdout = sp.PIPE, bufsize=10**8)
n = 0
im2 = []
try:
mog = cv2.BackgroundSubtractorMOG2(120,2,True)
while True:
raw_image = pipe.stdout.read(res[0]*res[1]*3)
# transform the byte read into a numpy array
image = np.fromstring(raw_image, dtype='uint8')
image = image.reshape((res[1],res[0],3))
rgbImg = image.copy()
image = cv2.cvtColor(image,cv2.COLOR_RGB2GRAY)
#image4 = rgbImg.copy()
#cv2.pyrMeanShiftFiltering(rgbImg,5,5,image4)
#image = cv2.cvtColor(image4,cv2.COLOR_RGB2GRAY)
image2 = mog.apply(image)
a,image2 = cv2.threshold(image2,150,255,cv2.THRESH_BINARY)
elem = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))
image2 = cv2.morphologyEx(image2,cv2.MORPH_OPEN,elem)
#image2 = cv2.medianBlur(image2,3)
a,image3 = cv2.threshold(image,105,255,cv2.THRESH_BINARY)
image3 = cv2.medianBlur(image3,3)
#image4 = cv2.adaptiveThreshold(image,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,5,-5)
dist_transform = cv2.distanceTransform(image3,1,5)
ret, sure_fg = cv2.threshold(dist_transform,0.7*dist_transform.max(),255,0)
#unknown = cv2.subtract(sure_bg,sure_fg)
image4 = np.uint8(sure_fg)
a,b = cv2.findContours(image3.copy(),cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(rgbImg,a,-1,(255,0,0))
cv2.imshow('vid',image)
cv2.imshow('im2',image2)
cv2.imshow('im3',image3)
cv2.imshow('rgb',rgbImg)
#cv2.imshow('im4',image4)
cv2.waitKey(1)
im2 = image
# throw away the data in the pipe's buffer.
#pipe.stdout.flush()
n += 1
print n
except:
print 'done',n
pipe.kill()
cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment