Ask Your Question

Revision history [back]

Unexpected shut down on Opencv

Hello there, Im a beginner in Python even in Opencv, but somehow ive reached the code below. Im 3 weeks with a desperate trouble: The recognition console shut down and write the .txt before the video ends, and have no idea why. I would appreciate any tip regardin this problem, Previous thanks.

  import sys
import argparse
import datetime
import time
import cv2
import numpy as np
import copy
import glob, os, sys
##import xlwt
##from xlwt import easyxf
##from xlwt import Workbook
##from xlwt import *



video_input =""       #initializing string variable for raw data input
video_input = raw_input("Enter the name of your text file - please use / backslash when typing in directory path: ")



filename= os.path.join(video_input)
filename_1= os.path.basename(filename)
directory_name = os.path.dirname(os.path.realpath(video_input))
print directory_name

filename_2= os.path.splitext(video_input)[0]
#date_time=time.ctime(os.path.getctime(filename))
#print date_time

cap = cv2.VideoCapture(filename)
#prepare to extract background
fgbg = cv2.BackgroundSubtractorMOG(150,16,False)
#kernel for dilation
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))

framecount = cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT)
print framecount

# Take first frame and make it grey. Will use for searching the template
ret, frame1= cap.read()

rows= frame1.shape[0]
cols= frame1.shape[1]
a=((rows/2)-30)
b=a+100
c=b+99
d=(cols/10)+4
gray1 = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY)
# Create a mask image for drawing purposes
mask_zeros = np.zeros_like(frame1)

#drawing the coordinates grid
cv2.line(mask_zeros,(0,a),(cols,a),(1,238,251),1)
cv2.line(mask_zeros,(0,b),(cols,b),(1,238,251),1)
cv2.line(mask_zeros,(0,c),(cols,c),(1,238,251),1)
cv2.line(mask_zeros,(d,a),(d,rows),(1,238,251),1)
cv2.line(mask_zeros,(d*2,a),(d*2,rows),(1,238,251),1)
cv2.line(mask_zeros,(d*3,a),(d*3,rows),(1,238,251),1)
cv2.line(mask_zeros,(d*4,a),(d*4,rows),(1,238,251),1)
cv2.line(mask_zeros,(d*5,a),(d*5,rows),(1,238,251),1)
cv2.line(mask_zeros,(d*6,a),(d*6,rows),(1,238,251),1)
cv2.line(mask_zeros,(d*7,a),(d*7,rows),(1,238,251),1)
cv2.line(mask_zeros,(d*8,a),(d*8,rows),(1,238,251),1)
cv2.line(mask_zeros,(d*9,a),(d*9,rows),(1,238,251),1)

#putting the text for coordinates grid
font = cv2.FONT_HERSHEY_SIMPLEX
#for X
cv2.putText(mask_zeros,"0",(0,a),font, 0.5,(1,238,251),1,cv2.CV_AA)
cv2.putText(mask_zeros,"100",(d,a),font, 0.5,(1,238,251),1,cv2.CV_AA)
cv2.putText(mask_zeros,"200",(d*2,a),font, 0.5,(1,238,251),1,cv2.CV_AA)
cv2.putText(mask_zeros,"300",(d*3,a),font, 0.5,(1,238,251),1,cv2.CV_AA)
cv2.putText(mask_zeros,"400",(d*4,a),font, 0.5,(1,238,251),1,cv2.CV_AA)
cv2.putText(mask_zeros,"500",(d*5,a),font, 0.5,(1,238,251),1,cv2.CV_AA)
cv2.putText(mask_zeros,"600",(d*6,a),font, 0.5,(1,238,251),1,cv2.CV_AA)
cv2.putText(mask_zeros,"700",(d*7,a),font, 0.5,(1,238,251),1,cv2.CV_AA)
cv2.putText(mask_zeros,"800",(d*8,a),font, 0.5,(1,238,251),1,cv2.CV_AA)
cv2.putText(mask_zeros,"900",(d*9,a),font, 0.5,(1,238,251),1,cv2.CV_AA)
#for Y
cv2.putText(mask_zeros,"0",(0,a+5),font, 0.5,(1,238,251),1,cv2.CV_AA)
cv2.putText(mask_zeros,"100",(0,b+5),font, 0.5,(1,238,251),1,cv2.CV_AA)
cv2.putText(mask_zeros,"200",(0,c+5),font, 0.5,(1,238,251),1,cv2.CV_AA)
cv2.putText(mask_zeros,"300",(0,rows-5),font, 0.5,(1,238,251),1,cv2.CV_AA)


mask_zeros=np.asarray(mask_zeros)
# Create some random colors
color = np.random.randint(0,255,(255,3))
#color=((0,0,255),(0,255,0),(255,0,0))
color= np.asarray(color)
listC=[]
listB=[]
frames = 0
while frames < framecount :
    ret, frame2 = cap.read()
    gray2 = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY)
    fgmask = fgbg.apply(frame2, learningRate=0.001)
    #fgmask = cv2.morphologyEx(fgmask, cv2.MORPH_OPEN, kernel)
    fgmask = cv2.dilate(fgmask,kernel,iterations = 2)
    #frameDelta = cv2.add(gray1,gray2)
    thresh = cv2.threshold(fgmask, 20, 255, cv2.THRESH_BINARY)[1]
    # dilate the thresholded image to fill in holes, then find contours
    # on thresholded image
    thresh = cv2.dilate(thresh, kernel, iterations=2)
    (cnts, _) = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

    counter=0
    listA=[]
    listW=[]
    listI=[]
    # loop over the contours
    for c in cnts: 

        # if the contour is too small, ignore it
        if cv2.contourArea(c) > 500:
           continue

        if cv2.contourArea(c) < 20:
           continue


        # compute the bounding box for the contour, draw it on the frame,
        # and update the text
        (x, y, w, h) = cv2.boundingRect(c)

        if x >770: ##Longitud de captura en x
            continue
        if x <= 770:
            listC.append(x)
            if w > 40:
                listW.append(w)
            groups=len(listW)
            if w < 40:
                listI.append(w)
            indiv=len(listI)
        listC_array=np.asarray(listC)
        listC_diff=np.diff(listC_array)
        listC_ones=np.where(listC_diff==1)
        standing =len(listC_ones)-1

        track_window=(x, y, w, h)

        if y < 240:
            continue


        a=(x,y)
        if any(a)>0:
            listA.append(a)
        listA_array=np.asarray(listA)    


        counter=0
        for i in listA:   
            cv2.circle(mask_zeros,(x+(w/2),y+h),1,color[counter],-1)
            img2 = cv2.rectangle(frame2, (x,y), (x+w,y+h),color[counter],2)
            counter +=1


        img = cv2.add(frame2,mask_zeros)



        cv2.imshow('img2',img)
        cv2.imshow('mask',mask_zeros)

        cv2.imwrite( directory_name+"frame1.jpg",frames)
        frames += 1


        k = cv2.waitKey(50) & 0xff  ## Velocidad de reproducción a menor mayor velocidad. Porque la duración disminuye?
        if k == 27:  ## si presiono k la velocidad es igual a 27
            break
        frame1=frame2.copy()

        listB.append(listA)



name=(filename_2)+".txt"
file = open(name,"w")   # Trying to create a new file or open one

with file as table:
    for row in listB:
        for cell in row:
            table.write(str(cell) + '\t')
        table.write('\n')
file.close()


cap.release()
cv2.destroyAllWindows()
click to hide/show revision 2
retagged

updated 2016-04-16 10:54:58 -0600

berak gravatar image

Unexpected shut down on Opencv

Hello there, Im a beginner in Python even in Opencv, but somehow ive reached the code below. Im 3 weeks with a desperate trouble: The recognition console shut down and write the .txt before the video ends, and have no idea why. I would appreciate any tip regardin this problem, Previous thanks.

  import sys
import argparse
import datetime
import time
import cv2
import numpy as np
import copy
import glob, os, sys
##import xlwt
##from xlwt import easyxf
##from xlwt import Workbook
##from xlwt import *



video_input =""       #initializing string variable for raw data input
video_input = raw_input("Enter the name of your text file - please use / backslash when typing in directory path: ")



filename= os.path.join(video_input)
filename_1= os.path.basename(filename)
directory_name = os.path.dirname(os.path.realpath(video_input))
print directory_name

filename_2= os.path.splitext(video_input)[0]
#date_time=time.ctime(os.path.getctime(filename))
#print date_time

cap = cv2.VideoCapture(filename)
#prepare to extract background
fgbg = cv2.BackgroundSubtractorMOG(150,16,False)
#kernel for dilation
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))

framecount = cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT)
print framecount

# Take first frame and make it grey. Will use for searching the template
ret, frame1= cap.read()

rows= frame1.shape[0]
cols= frame1.shape[1]
a=((rows/2)-30)
b=a+100
c=b+99
d=(cols/10)+4
gray1 = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY)
# Create a mask image for drawing purposes
mask_zeros = np.zeros_like(frame1)

#drawing the coordinates grid
cv2.line(mask_zeros,(0,a),(cols,a),(1,238,251),1)
cv2.line(mask_zeros,(0,b),(cols,b),(1,238,251),1)
cv2.line(mask_zeros,(0,c),(cols,c),(1,238,251),1)
cv2.line(mask_zeros,(d,a),(d,rows),(1,238,251),1)
cv2.line(mask_zeros,(d*2,a),(d*2,rows),(1,238,251),1)
cv2.line(mask_zeros,(d*3,a),(d*3,rows),(1,238,251),1)
cv2.line(mask_zeros,(d*4,a),(d*4,rows),(1,238,251),1)
cv2.line(mask_zeros,(d*5,a),(d*5,rows),(1,238,251),1)
cv2.line(mask_zeros,(d*6,a),(d*6,rows),(1,238,251),1)
cv2.line(mask_zeros,(d*7,a),(d*7,rows),(1,238,251),1)
cv2.line(mask_zeros,(d*8,a),(d*8,rows),(1,238,251),1)
cv2.line(mask_zeros,(d*9,a),(d*9,rows),(1,238,251),1)

#putting the text for coordinates grid
font = cv2.FONT_HERSHEY_SIMPLEX
#for X
cv2.putText(mask_zeros,"0",(0,a),font, 0.5,(1,238,251),1,cv2.CV_AA)
cv2.putText(mask_zeros,"100",(d,a),font, 0.5,(1,238,251),1,cv2.CV_AA)
cv2.putText(mask_zeros,"200",(d*2,a),font, 0.5,(1,238,251),1,cv2.CV_AA)
cv2.putText(mask_zeros,"300",(d*3,a),font, 0.5,(1,238,251),1,cv2.CV_AA)
cv2.putText(mask_zeros,"400",(d*4,a),font, 0.5,(1,238,251),1,cv2.CV_AA)
cv2.putText(mask_zeros,"500",(d*5,a),font, 0.5,(1,238,251),1,cv2.CV_AA)
cv2.putText(mask_zeros,"600",(d*6,a),font, 0.5,(1,238,251),1,cv2.CV_AA)
cv2.putText(mask_zeros,"700",(d*7,a),font, 0.5,(1,238,251),1,cv2.CV_AA)
cv2.putText(mask_zeros,"800",(d*8,a),font, 0.5,(1,238,251),1,cv2.CV_AA)
cv2.putText(mask_zeros,"900",(d*9,a),font, 0.5,(1,238,251),1,cv2.CV_AA)
#for Y
cv2.putText(mask_zeros,"0",(0,a+5),font, 0.5,(1,238,251),1,cv2.CV_AA)
cv2.putText(mask_zeros,"100",(0,b+5),font, 0.5,(1,238,251),1,cv2.CV_AA)
cv2.putText(mask_zeros,"200",(0,c+5),font, 0.5,(1,238,251),1,cv2.CV_AA)
cv2.putText(mask_zeros,"300",(0,rows-5),font, 0.5,(1,238,251),1,cv2.CV_AA)


mask_zeros=np.asarray(mask_zeros)
# Create some random colors
color = np.random.randint(0,255,(255,3))
#color=((0,0,255),(0,255,0),(255,0,0))
color= np.asarray(color)
listC=[]
listB=[]
frames = 0
while frames < framecount :
    ret, frame2 = cap.read()
    gray2 = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY)
    fgmask = fgbg.apply(frame2, learningRate=0.001)
    #fgmask = cv2.morphologyEx(fgmask, cv2.MORPH_OPEN, kernel)
    fgmask = cv2.dilate(fgmask,kernel,iterations = 2)
    #frameDelta = cv2.add(gray1,gray2)
    thresh = cv2.threshold(fgmask, 20, 255, cv2.THRESH_BINARY)[1]
    # dilate the thresholded image to fill in holes, then find contours
    # on thresholded image
    thresh = cv2.dilate(thresh, kernel, iterations=2)
    (cnts, _) = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

    counter=0
    listA=[]
    listW=[]
    listI=[]
    # loop over the contours
    for c in cnts: 

        # if the contour is too small, ignore it
        if cv2.contourArea(c) > 500:
           continue

        if cv2.contourArea(c) < 20:
           continue


        # compute the bounding box for the contour, draw it on the frame,
        # and update the text
        (x, y, w, h) = cv2.boundingRect(c)

        if x >770: ##Longitud de captura en x
            continue
        if x <= 770:
            listC.append(x)
            if w > 40:
                listW.append(w)
            groups=len(listW)
            if w < 40:
                listI.append(w)
            indiv=len(listI)
        listC_array=np.asarray(listC)
        listC_diff=np.diff(listC_array)
        listC_ones=np.where(listC_diff==1)
        standing =len(listC_ones)-1

        track_window=(x, y, w, h)

        if y < 240:
            continue


        a=(x,y)
        if any(a)>0:
            listA.append(a)
        listA_array=np.asarray(listA)    


        counter=0
        for i in listA:   
            cv2.circle(mask_zeros,(x+(w/2),y+h),1,color[counter],-1)
            img2 = cv2.rectangle(frame2, (x,y), (x+w,y+h),color[counter],2)
            counter +=1


        img = cv2.add(frame2,mask_zeros)



        cv2.imshow('img2',img)
        cv2.imshow('mask',mask_zeros)

        cv2.imwrite( directory_name+"frame1.jpg",frames)
        frames += 1


        k = cv2.waitKey(50) & 0xff  ## Velocidad de reproducción a menor mayor velocidad. Porque la duración disminuye?
        if k == 27:  ## si presiono k la velocidad es igual a 27
            break
        frame1=frame2.copy()

        listB.append(listA)



name=(filename_2)+".txt"
file = open(name,"w")   # Trying to create a new file or open one

with file as table:
    for row in listB:
        for cell in row:
            table.write(str(cell) + '\t')
        table.write('\n')
file.close()


cap.release()
cv2.destroyAllWindows()