Detect moving objects by Back subtraction
- leomurayama7
- Feb 2, 2017
- 3 min read
忘れないうちに、ラズパイ上でpythonで書いたDetection.pyのコードを載せときます。
# coding:utf-8 import cv2 import numpy as np import matplotlib.pyplot as plt import time import wx pushB = 0 # if the button B was pushed, pushB = 1 SeatSum = 6 middleY = 120 maxValue =0 comeIn = 0 goOut = 0 ResultImg = np.zeros((240,320,3),np.uint8) ResultImg[:,:]= (255,255,255) #pushB = 0 # if the button B was pushed, pushB = 1 Total = 1 # total number of people in the room #define kernel for the dilation kernel = np.ones((3,3),np.uint8) #capture video frame cap = cv2.VideoCapture(0) # define the center Y axis for 5 people centerY = [[np.nan] for j in range(5)] #print(centerY) # define array oftime variable frame = np.array([]) frame = np.append(frame,0) #print(time) t=0 # define array of total number of people total = np.array([]) total = np.append(total,0) #print(total) # define array of the surface of object1 obj_surface = np.array([]) obj_surface = np.append(obj_surface,0) # define detected object number objNum=0 # define last surface prev_surface = [500 for j in range(5)] # value of one contour: if 2 people exist in one contour, value = 2 value = [1 for j in range(5)] # define person[previons_state][current_state] # state = 0: is inside # state = 1: is outside person = [[-1 for i in range(2)] for j in range(5)] mx = [0 for j in range(5)] my = [0 for j in range(5)] prev_my = [0 for j in range(5)] font = cv2.FONT_HERSHEY_DUPLEX font2 = cv2.FONT_HERSHEY_TRIPLEX time_before = time.time() while True: # read one frame ret, frame1 = cap.read() petit1 = cv2.resize(frame1,(320,240)) gray1 = cv2.cvtColor(petit1,cv2.COLOR_BGR2GRAY) cv2.imshow('camera capture',petit1) cv2.moveWindow('camera capture',20,55) k = cv2.waitKey(10) if k == 98: ret, frame2 = cap.read() petit2 = cv2.resize(frame2,(320,240)) gray2 = cv2.cvtColor(petit2,cv2.COLOR_BGR2GRAY) height, width, channels = frame2.shape pushB +=1 startTime = time.time() if pushB == 1: cv2.imshow('Detection Result',ResultImg) cv2.moveWindow('Detection Result',360,340) diffimg = cv2.absdiff(gray1,gray2) #cv2.imshow('Sabun',diffimg) ret, thresh = cv2.threshold(diffimg,60,255,cv2.THRESH_BINARY) #cv2.imshow('Thresh',thresh) dilation = cv2.dilate(thresh,kernel,iterations = 1) cv2.imshow('Different image',dilation) cv2.moveWindow('Different image',20,340) contours, hierarchy = cv2.findContours(dilation,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) id = 0 t +=1 #print "t: " +str(t) frame = np.append(frame,t) total = np.append(total,Total) for j in range(5): centerY[j].append(np.nan) #print(centerY[0]) obj_surface = np.append(obj_surface,np.nan) cv2.line(petit1,(0,120),(319,120),(0,0,255),2) tb = time.time() for cnt in contours: if cv2.contourArea(cnt) > 4000: M = cv2.moments(cnt) mx[id] = int(M['m10']/M['m00']) my[id] = int(M['m01']/M['m00']) obj_surface[-1] = cv2.contourArea(cnt) #print "prev_s: "+str(prev_surface)+"current_s: " +str(cv2.contourArea(cnt)) prev_surface[id] = cv2.contourArea(cnt) prev_my[id] = my[id] # find the rectangle realise the smallest serface rect = cv2.minAreaRect(cnt) box = cv2.cv.BoxPoints(rect) box = np.int0(box) centerY[id][-1] = my[id] # default: decide the start situation if person[id][0] < 0 and person[id][1] < 0: if my[id] <= 120: person[id][0]= 1 else : person[id][0]= 0 #print "a: " +str(id)+ " prev: " +str(person[id][0])+ "now: "+str(person[id][1]) #take the current situation if my[id] <= 120: person[id][1] = 1 else : person[id][1] = 0 #print "b: "+str(id)+ " prev: " +str(person[id][0])+ " now: "+str(person[id][1]) cv2.drawContours(petit1,[box],0,(255,0,0),2) cv2.circle(petit1,(mx[id],my[id]),3,(0,255,0),-1) #cv2.putText(petit1,str(value[id]),(mx[id],my[id]),font,2.0,(0,255,0),4) #if person's state changed in the prev and current situation if person[id][0] != person[id][1]: if person[id][0] == 1 : print "one person goes out!" #cv2.drawContours(petit1,[box],0,(0,0,255),2) cv2.line(petit1,(0,120),(319,120),(0,255,0),2) person[id][0] = 0 person[id][1] = -1 Total -=1 goOut += 1 #print str(Total) else : print "one person comes in!" #cv2.drawContours(petit1,[box],0,(0,0,255),2) cv2.line(petit1,(0,120),(319,120),(0,255,0),2) person[id][0] = 1 person[id][1] = -1 Total +=1 comeIn +=1 #print str(Total) #print str(id) if id == 1: objNum =1 id +=1 ResultImg[:,:]= (255,255,255) cv2.putText(ResultImg,"people come in: "+str(comeIn),(10,50),font2,0.6,(255,0,0)) cv2.putText(ResultImg,"people go out: "+str(goOut),(10,20),font2,0.6,(255,0,0)) cv2.putText(ResultImg,"total num of seats: "+str(SeatSum),(10,110),font2,0.6,(0,0,0)) cv2.putText(ResultImg,"num of remaining seats: "+str(SeatSum-Total),(10,170),font2,0.6,(0,0,255)) cv2.putText(ResultImg,"Sum of people inside: "+str(Total),(10,140),font2,0.6,(0,0,0)) if id == 0 : person = [[-1 for i in range(2)] for j in range(5)] cv2.imshow('Contours',petit1) cv2.moveWindow('Contours',360,55) ta = time.time() td = tb - ta time_length = abs(ta - startTime) cv2.putText(ResultImg,"Time duration: "+str(round(time_length,2))+" sec",(10,200),font2,0.6,(0,0,0)) cv2.putText(ResultImg,"Frame's number: "+str(t),(10,230),font2,0.6,(0,0,0)) #print(td) if k == 27: break print "t= "+ str(t) time_after = time.time() time_diff = time_after - time_before print(time_diff) print "frame/sec = " + str(t/time_diff) plt.subplot(2,1,1) plt.plot(frame,centerY[0],'b--x') #print str(objNum) if objNum == 1: plt.plot(frame,centerY[1],'g--x') plt.title("Movement of the detected oject") plt.ylim(0,240) plt.xlim(0,t) plt.plot([0,t],[120,120],"r--") #plt.plot([0,t],[100,100],"r--") #plt.plot([0,t],[400,400],"r--") plt.xlabel("frame") plt.ylabel("Y axis of object(pixel)") plt.subplot(2,1,2) plt.bar(frame,total,align = "center") plt.ylim(0,5) plt.xlim(0,t) plt.ylabel("Number of people in the room") #plt.subplot(2,1,2) #plt.bar(frame,obj_surface,align = "center") #plt.ylim(0,25000) #plt.plot([0,t],[0,0],"r--") #plt.xlim(0,t) #plt.ylabel("Surface of the object(pixel)") plt.show() cap.release() cv2.destroyAllWindows()
Commentaires