Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

vi class(14th) #52

Open
HaebinKim opened this issue May 13, 2018 · 5 comments
Open

vi class(14th) #52

HaebinKim opened this issue May 13, 2018 · 5 comments
Assignees
Labels

Comments

@HaebinKim
Copy link
Collaborator

HaebinKim commented May 13, 2018

14th

  • 14th 요구사항 적용

1. 코드

from observer import *
import cv2
import numpy as np
import time

class Vi(Observer):
    BREAK_AWAY = ""
    RETURN_BACK = ""
    UNTILL_BREAK = ""
    frame = 0
    my_contours = []
    st_frame = 0
    out_frame = 0
    sz_frame = 0
    os_frame = 0
    ob_frame = 0
    sz_size = 0
    cap = 0
    vi_width = 0
    vi_height = 0
    contours = []
    edges = []
    mx = 0
    my = 0
    sz_x = 0
    sz_y = 0
    sz_w = 0
    sz_h = 0
    def __init__(self,Push):
	self.reSet(Push)
        self.BREAK_AWAY = "Baby is Zone out"
        self.RETURN_BACK = "Baby is Zone in"
        self.UNTILL_BREAK = "Baby is Zone out long time"
        self.mPush = Push
        self.frame = 0
        self.my_contours = []
        self.st_frame = 0
        self.out_frame = 0
        self.sz_frame = 15
        self.os_frame = 10
        self.ob_frame = 1
        self.sz_size = 100
        self.cap = 0
        self.vi_width = 0
        self.vi_height = 0
        self.contours = []
        self.edges = []
        self.mx = 0
        self.my = 0
        self.sz_x = 0
        self.sz_y = 0
        self.sz_w = 0
        self.sz_h = 0
        self.openCamera()
        # self.run()
		
   def outcheck(self):
        if self.mx > self.sz_x and self.mx < self.sz_x + self.sz_w and self.my > self.sz_y and self.my < self.sz_y + self.sz_h:
            return 0
        else:
            return 1

    def openCamera(self):
        self.cap = cv2.VideoCapture('test2.mp4')
        self.vi_width = int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH))
        self.vi_height = int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

    def getCapture(self):
        ret, self.frame = self.cap.read()
        if self.frame is None: return;
        frgray = cv2.cvtColor(self.frame, cv2.COLOR_BGR2GRAY)
        kernel = np.ones((3, 3), np.float32) / 25
        dst = cv2.filter2D(frgray, -1, kernel)
        self.edges = cv2.Canny(dst, 50, 100)
        _, self.contours, _ = cv2.findContours(self.edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    def getMoment(self):
        max_area = 0;
        ci = 0
        for i in range(len(self.contours)):
            cnt = self.contours[i]
            area = cv2.contourArea(cnt)
            if (area > max_area):
                max_area = area
                ci = i
        contours = self.contours[ci]
        mmt = cv2.moments(contours)
        if mmt['m00'] != 0:
            self.mx = int(mmt['m10'] / mmt['m00'])
            self.my = int(mmt['m01'] / mmt['m00'])
        cv2.rectangle(self.frame, (int(self.mx), int(self.my)), (int(self.mx), int(self.my)), (0, 0, 255), 8)
        if self.frame is None: return;
        # cv2.imshow('fgmask', self.frame)
        # cv2.imshow('EDGES', self.edges)

    def getSaftyZone(self):
        for i in range(0, self.vi_width):
            for j in range(0, self.vi_height):
                if self.edges[j, i] == 0:
                    self.edges[j, i] = 255
                else:
                    self.edges[j, i] = 0
                    self.my_contours.append([i, j])
        B = np.array(self.my_contours)
        self.sz_x, self.sz_y, self.sz_w, self.sz_h = cv2.boundingRect(B)
        self.setSafttyZoneSize()
        cv2.rectangle(self.frame, (int(self.sz_x), int(self.sz_y)),
                      (int(self.sz_x + self.sz_w), int(self.sz_y + self.sz_h)), (0, 0, 255), 3)

    def setSafttyZoneSize(self):
        tmp_rx = self.sz_x
        tmp_ry = self.sz_y
        self.sz_x = tmp_rx + int((100 - self.sz_size) / 200 * self.sz_w)
        self.sz_y = tmp_ry + int((100 - self.sz_size) / 200 * self.sz_h)
        self.sz_w = self.sz_size / 100 * self.sz_w
        self.sz_h = self.sz_size / 100 * self.sz_h

    def checkSaftyZone(self):
        if self.outCheck() == 1:
            self.out_frame = self.out_frame + 1
        else:
            if self.out_frame > 30:
                self.out_frame = 0
                return (self.RETURN_BACK)
        if self.out_frame == 30:
            return (self.BREAK_AWAY)
        if self.out_frame > 0 and self.out_frame % 100 == 0:
            return (self.UNTILL_BREAK)
        return 0

    def checkObserveFrame(self):
        self.st_frame = self.st_frame + 1
        if self.st_frame < self.os_frame: return 1
        if self.st_frame != self.sz_frame:
            if self.st_frame % self.ob_frame != 0 and self.out_frame == 0:
                return 1
            if self.st_frame % 5 != 0:
                return 1
        return 0

    def run(self):
        while(True):
            # 사진요청이 왓다면 사진파일 만드는 일까지, 만들기만 할것 전송은 나중에 짤예정
            item = self.popRQ()
            if (item != False):
                self.mPush.insertMSG(item.user,item.msg)
		#cv2.imshow("Captured Image", self.frame)

            ##여기서부터는 평소처럼 관측
            if(True): #이탈 시
		print("running Vi")
                while (True):
                    if self.checkObserveFrame() == 1:
                        continue
                    self.getCapture()
                    self.getMoment()
                    if self.st_frame == self.sz_frame:
                        self.getSaftyZone()
                    MSG = self.checkSaftyZone()
                    if MSG != 0:
                        self.mPush.insertMSG('ALL',"PUSH :vi 스레드 >>" + MSG )
                    k = cv2.waitKey(30) & 0xff
                    if k == 27:
                        break
                self.cap.release()
                cv2.destroyAllWindows()
				
                time.sleep(5)
                self.mPush.insertMSG('ALL',"PUSH :vi 스레드")

13th

  • General 2.0 양식 맞춰서 업데이트

1. 코드

from observer import *
import cv2
import numpy as np
import time

class Vi(Observer):
BREAK_AWAY = ""
RETURN_BACK = ""
UNTILL_BREAK = ""
frame = 0
my_contours = []
st_frame = 0
out_frame = 0
sz_frame = 0
os_frame = 0
ob_frame = 0
sz_size = 0
cap = 0
vi_width = 0
vi_height = 0
contours = []
edges = []
mx = 0
my = 0
sz_x = 0
sz_y = 0
sz_w = 0
sz_h = 0
def init(self,Push):
Observer.init(Observer,Push)
self.BREAK_AWAY = "Baby is Zone out"
self.RETURN_BACK = "Baby is Zone in"
self.UNTILL_BREAK = "Baby is Zone out long time"
self.mPush = Push
self.frame = 0
self.my_contours = []
self.st_frame = 0
self.out_frame = 0
self.sz_frame = 15
self.os_frame = 10
self.ob_frame = 1
self.sz_size = 100
self.cap = 0
self.vi_width = 0
self.vi_height = 0
self.contours = []
self.edges = []
self.mx = 0
self.my = 0
self.sz_x = 0
self.sz_y = 0
self.sz_w = 0
self.sz_h = 0
self.openCamera()
# self.run()

def out(self):
    if self.mx > self.sz_x and self.mx < self.sz_x + self.sz_w and self.my > self.sz_y and self.my < self.sz_y + self.sz_h:
        return 0
    else:
        return 1

def openCamera(self):
    self.cap = cv2.VideoCapture('test2.mp4')
    self.vi_width = int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    self.vi_height = int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

def getCapture(self):
    ret, self.frame = self.cap.read()
    if self.frame is None: return;
    frgray = cv2.cvtColor(self.frame, cv2.COLOR_BGR2GRAY)
    kernel = np.ones((3, 3), np.float32) / 25
    dst = cv2.filter2D(frgray, -1, kernel)
    self.edges = cv2.Canny(dst, 50, 100)
    _, self.contours, _ = cv2.findContours(self.edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

def getMoment(self):

    max_area = 0;
    ci = 0
    for i in range(len(self.contours)):
        cnt = self.contours[i]
        area = cv2.contourArea(cnt)
        if (area > max_area):
            max_area = area
            ci = i
    contours = self.contours[ci]
    mmt = cv2.moments(contours)
    if mmt['m00'] != 0:
        self.mx = int(mmt['m10'] / mmt['m00'])
        self.my = int(mmt['m01'] / mmt['m00'])
    cv2.rectangle(self.frame, (int(self.mx), int(self.my)), (int(self.mx), int(self.my)), (0, 0, 255), 8)
    if self.frame is None: return;
    # cv2.imshow('fgmask', self.frame)
    # cv2.imshow('EDGES', self.edges)

def getSaftyZone(self):

    for i in range(0, self.vi_width):
        for j in range(0, self.vi_height):
            if self.edges[j, i] == 0:
                self.edges[j, i] = 255
            else:
                self.edges[j, i] = 0
                self.my_contours.append([i, j])
    B = np.array(self.my_contours)
    self.sz_x, self.sz_y, self.sz_w, self.sz_h = cv2.boundingRect(B)
    self.setSafttyZoneSize()
    cv2.rectangle(self.frame, (int(self.sz_x), int(self.sz_y)),
                  (int(self.sz_x + self.sz_w), int(self.sz_y + self.sz_h)), (0, 0, 255), 3)

def setSafttyZoneSize(self):

    tmp_rx = self.sz_x
    tmp_ry = self.sz_y
    self.sz_x = tmp_rx + int((100 - self.sz_size) / 200 * self.sz_w)
    self.sz_y = tmp_ry + int((100 - self.sz_size) / 200 * self.sz_h)
    self.sz_w = self.sz_size / 100 * self.sz_w
    self.sz_h = self.sz_size / 100 * self.sz_h

def checkSaftyZone(self):

    if self.out() == 1:
        self.out_frame = self.out_frame + 1
    else:
        if self.out_frame > 30:
            self.out_frame = 0
            return (self.RETURN_BACK)
    if self.out_frame == 30:
        return (self.BREAK_AWAY)
    if self.out_frame > 0 and self.out_frame % 100 == 0:
        return (self.UNTILL_BREAK)
    return 0;

def checkObserveFrame(self):
    self.st_frame = self.st_frame + 1
    if self.st_frame < self.os_frame: return 1
    if self.st_frame != self.sz_frame:
        if self.st_frame % self.ob_frame != 0 and self.out_frame == 0:
            return 1
        if self.st_frame % 5 != 0:
            return 1
    return 0

def run(self):
    while(True):
        item = self.popRQ()
        if (item != False):
            print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!vi:  %s request %s" % (item.user, item.msg))
            cv2.imshow("Captured Image", self.frame)


        if(True):
            print("running Vi")
            while (True):
                if self.checkObserveFrame() == 1:
                    continue
                self.getCapture()
                self.getMoment()
                if self.st_frame == self.sz_frame:
                    self.getSaftyZone()
                MSG = self.checkSaftyZone()
                if MSG != 0:
                    self.mPush.insertMSG(MSG)
                k = cv2.waitKey(30) & 0xff
                if k == 27:
                    break
            self.cap.release()
            cv2.destroyAllWindows()

            time.sleep(2)
            self.mPush.insertMSG("-----------------Vi thread")

11th

image

  • 11th 요구사항 구현

1. 코드

import numpy as np
import cv2

class Vi():
    BREAK_AWAY = ""
    RETURN_BACK = ""
    UNTILL_BREAK = ""
    frame = 0
    my_contours = []
    st_frame = 0
    out_frame = 0
    sz_frame = 0  # 세이프티존 생성시 기준프레임
    os_frame = 0
    ob_frame = 0  # 관측 프레임
    sz_size = 0  # 세이프티존 사이즈
    cap = 0
    vi_width = 0    #비디오 너비
    vi_height = 0   #비디오 높이
    contours = []   #영상처리후의 윤곽
    edges = []
    mx = 0  #무게중심 x좌표
    my = 0  #무게중심 y좌표
    sz_x = 0    #세이프티존 최상단좌측 x좌표
    sz_y = 0    #세이프티존 최상단좌측Y좌표
    sz_w = 0    #세이프티존 너비
    sz_h = 0    #세이프티존 높이

    def __init__(self,Push):
        self.BREAK_AWAY = "아이의 존이탈이 감지되었습니다!"
        self.RETURN_BACK = "아이가 Safty Zone 안으로 돌아왔습니다!"
        self.UNTILL_BREAK = "아이가 여전히 존이탈 중입니다!"
        self.mPush = Push
        self.frame = 0
        self.my_contours = []
        self.st_frame = 0
        self.out_frame = 0
        self.sz_frame = 15
        self.os_frame = 10
        self.ob_frame = 1
        self.sz_size = 100
        self.cap = 0
        self.vi_width = 0
        self.vi_height = 0
        self.contours = []
        self.edges = []
        self.mx = 0
        self.my = 0
        self.sz_x = 0
        self.sz_y = 0
        self.sz_w = 0
        self.sz_h = 0
        self.openCamera()
        self.run()

    def out(self):
        if self.mx > self.sz_x and self.mx < self.sz_x + self.sz_w and self.my > self.sz_y and self.my < self.sz_y + self.sz_h:
            return 0
        else:
            return 1

    def openCamera(self):
        self.cap = cv2.VideoCapture('test2.mp4')  # 웹켐쓸거면인자 0 , 영상파일 열거면 이름 넣을것
        self.vi_width = int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH))
        self.vi_height = int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

    def getCapture(self):
        ret, self.frame = self.cap.read()
        if self.frame is None: return;
        frgray = cv2.cvtColor(self.frame, cv2.COLOR_BGR2GRAY)
        kernel = np.ones((3, 3), np.float32) / 25
        dst = cv2.filter2D(frgray, -1, kernel)
        self.edges = cv2.Canny(dst, 50, 100)
        _, self.contours, _ = cv2.findContours(self.edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    def getMoment(self):
        # moment이용 무게중심을 구함
        max_area = 0;
        ci = 0
        for i in range(len(self.contours)):
            cnt = self.contours[i]
            area = cv2.contourArea(cnt)
            if (area > max_area):
                max_area = area
                ci = i
        contours = self.contours[ci]
        mmt = cv2.moments(contours)
        if mmt['m00'] != 0:
            self.mx = int(mmt['m10'] / mmt['m00'])
            self.my = int(mmt['m01'] / mmt['m00'])
        cv2.rectangle(self.frame, (int(self.mx), int(self.my)), (int(self.mx), int(self.my)), (0, 0, 255), 8)
        if self.frame is None: return;
        cv2.imshow('fgmask', self.frame)
        cv2.imshow('EDGES', self.edges)

    def getSaftyZone(self):
        # 세이프티존 생성
        for i in range(0, self.vi_width):
            for j in range(0, self.vi_height):
                if self.edges[j, i] == 0:
                    self.edges[j, i] = 255
                else:
                    self.edges[j, i] = 0
                    self.my_contours.append([i, j])
        B = np.array(self.my_contours)
        self.sz_x, self.sz_y, self.sz_w, self.sz_h = cv2.boundingRect(B)
        self.setSafttyZoneSize()
        cv2.rectangle(self.frame, (int(self.sz_x), int(self.sz_y)),
                      (int(self.sz_x + self.sz_w), int(self.sz_y + self.sz_h)), (0, 0, 255), 3)

    def setSafttyZoneSize(self):
        # 세이프티존 크기 설정
        tmp_rx = self.sz_x
        tmp_ry = self.sz_y
        self.sz_x = tmp_rx + int((100 - self.sz_size) / 200 * self.sz_w)
        self.sz_y = tmp_ry + int((100 - self.sz_size) / 200 * self.sz_h)
        self.sz_w = self.sz_size / 100 * self.sz_w
        self.sz_h = self.sz_size / 100 * self.sz_h

    def checkSaftyZone(self):
        # 존이탈
        if self.out() == 1:
            self.out_frame = self.out_frame + 1
        else:
            if self.out_frame > 30:
                self.out_frame = 0
                return(self.RETURN_BACK)
        if self.out_frame == 30:
            return(self.BREAK_AWAY)
        if self.out_frame > 0 and self.out_frame % 100 == 0:
            return(self.UNTILL_BREAK)
        return 0;

    def checkObserveFrame(self):
        self.st_frame = self.st_frame + 1
        if self.st_frame < self.os_frame: return 1
        if self.st_frame != self.sz_frame:
            if self.st_frame % self.ob_frame != 0 and self.out_frame == 0:
                return 1
            if self.st_frame % 5 != 0:
                return 1
        return 0

    def run(self):
        while(True):
            if self.checkObserveFrame() == 1 :
               continue
            self.getCapture()
            self.getMoment()
            if self.st_frame == self.sz_frame:
                self.getSaftyZone()
            MSG = self.checkSaftyZone()
            if MSG != 0 :
                self.mPush.insertMSG(MSG)
            k = cv2.waitKey(30) & 0xff
            if k == 27:
                break
        self.cap.release()
        cv2.destroyAllWindows()

2. 테스트

테스트영상 3번

  • 캐니함수 낮은경계값 : 50 높은 경계값: 100 (디폴트)
    image

테스트영상 4번

  • 캐니함수 낮은경계값 : 50 높은 경계값: 100 (디폴트)
    image

  • 캐니함수 낮은경계값 : 50 높은 경계값: 150
    image

테스트영상 5번

  • 캐니함수 낮은경계값 : 50 높은 경계값: 100 (디폴트)
    image

  • 캐니함수 낮은경계값 : 50 높은 경계값: 120
    image

테스트영상 6번 (카메라자체가 살짝 움직임)

  • 캐니함수 낮은경계값 : 50 높은 경계값: 100 (디폴트)
    image

  • 캐니함수 낮은경계값 : 100 높은 경계값: 200
    image

3. 결과

  • 아기만 움직이는경우 높은 정확도를 보임
  • 아기외에 다른 물체가 움직임이 포착 될 경우 캐니함수 값변경으로 어느정도 해결이 가능(값 변경하는 함수 추가 필요)
  • 카메라 자체가 움직이면 노답이니 만들때 고정 필요

10th

1. 테스트

image

  • 9th에 있던 에러 해결
  • 10th 요구사항 구현

2. 코드

import numpy as np
import cv2

class Vi():
    my_contours = []
    st_frame = 0
    out_frame = 0
    sz_frame = 0  # 세이프티존 생성시 기준프레임
    os_frame = 0
    ob_frame = 0  # 관측 프레임
    sz_size = 0  # 세이프티존 사이즈
    def __init__(self,Push):
        self.mPush = Push
        self.my_contours = []
        self.st_frame = 0
        self.out_frame = 0
        self.sz_frame = 15
        self.os_frame = 10
        self.ob_frame = 1
        self.sz_size = 100
        self.run()
    def out(self,mx, my, rx, ry, w, h):
        if mx > rx and mx < rx + w and my > ry and my < ry + h:
            return 0
        else:
            return 1
    def run(self):
        cap = cv2.VideoCapture('test2.mp4')  # 웹켐쓸거면인자 0 , 영상파일 열거면 이름 넣을것
        #fgbg = cv2.createBackgroundSubtractorMOG2()

        width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
        height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

        mx = 0
        my = 0
        sz_x = 0
        sz_y = 0
        sz_w = 0
        sz_h = 0
        while(True):
            self.st_frame = self.st_frame + 1
            if self.st_frame < self.os_frame : continue
            if self.st_frame != self.sz_frame:
                if self.st_frame % self.ob_frame != 0 and self.out_frame == 0:
                    continue
                if self.st_frame % 5 != 0:
                    continue

            # 영상처리
            ret, frame = cap.read()
            if frame is None: break;
            frgray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            kernel = np.ones((3, 3), np.float32) / 25
            dst = cv2.filter2D(frgray, -1, kernel)
            edges = cv2.Canny(dst, 50, 100)
            _, contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

            # moment이용 무게중심을 구함
            max_area = 0;
            ci = 0
            for i in range(len(contours)):
                cnt = contours[i]
                area = cv2.contourArea(cnt)
                if (area > max_area):
                    max_area = area
                    ci = i
            contours = contours[ci]
            mmt = cv2.moments(contours)
            if mmt['m00'] != 0:
                mx = int(mmt['m10'] / mmt['m00'])
                my = int(mmt['m01'] / mmt['m00'])

            # 세이프티존 생성
            if self.st_frame == self.sz_frame:
                for i in range(0, width):
                    for j in range(0, height):
                        if edges[j, i] == 0:
                            edges[j, i] = 255
                        else:
                            edges[j, i] = 0
                            self.my_contours.append([i, j])
                B = np.array(self.my_contours)
                sz_x, sz_y, sz_w, sz_h = cv2.boundingRect(B)

                # 세이프티존 크기 설정
                tmp_rx = sz_x
                tmp_ry = sz_y
                sz_x = tmp_rx + int((100 - self.sz_size) / 200 * sz_w)
                sz_y = tmp_ry + int((100 - self.sz_size) / 200 * sz_h)
                sz_w = self.sz_size / 100 * sz_w
                sz_h = self.sz_size / 100 * sz_h

            # 존이탈
            if self.out(mx, my, sz_x, sz_y, sz_w, sz_h) == 1:
                self.out_frame = self.out_frame + 1
            else:
                if self.out_frame > 30:
                    self.mPush.insertMSG("아이가 Safty Zone 안으로 돌아왔습니다!")
                    self.out_frame = 0
            if self.out_frame == 30:
                print("존이탈!!!!")
                self.mPush.insertMSG("아이의 존이탈이 감지되었습니다!")

            if self.out_frame > 0 and self.out_frame % 100 == 0 :
                self.mPush.insertMSG("아이가 여전히 존이탈 중입니다!")

            if self.st_frame > self.sz_frame:
                cv2.rectangle(frame, (int(mx), int(my)), (int(mx), int(my)), (0, 0, 255), 8)
                cv2.rectangle(frame, (int(sz_x), int(sz_y)), (int(sz_x + sz_w), int(sz_y + sz_h)), (0, 0, 255), 3)

            cv2.imshow('fgmask', frame)
            #cv2.imshow('frame', fgmask)
            #cv2.imshow('dst2', dst2)
            cv2.imshow('EDGES', edges)

            k = cv2.waitKey(30) & 0xff
            if k == 27:
                break
        cap.release()
        cv2.destroyAllWindows()


9th

1. 테스트

image

  • 존이탈시 메시지 보내는것은 되지만 동영상 종료시 에러발생(카메라로 관측시 에러가 없을 것으로 예상)
  • 현재는 존 이탈 후 30프레임지나도 존 이탈상태인경우 메세지를 보내고 다시 30프레임이 지나도 존 이탈상태인경우 메세지를 또 보내는상태, 어떻게 처리할지 생각해볼 필요 있음

2. 코드

import numpy as np
import cv2

class Vi():
    my_contours = []
    st_frame = 0
    out_frame = 0
    sz_frame = 0  # 세이프티존 생성시 기준프레임
    ob_frame = 0  # 관측 프레임
    sz_size = 0  # 세이프티존 사이즈
    def __init__(self,Push):
        self.mPush = Push
        self.my_contours = []
        self.st_frame = 0
        self.out_frame = 0
        self.sz_frame = 5
        self.ob_frame = 1
        self.sz_size = 100
        self.run()
    def out(self,mx, my, rx, ry, w, h):
        if mx > rx and mx < rx + w and my > ry and my < ry + h:
            return 0
        else:
            return 1
    def run(self):
        cap = cv2.VideoCapture('test2.mp4')  # 웹켐쓸거면인자 0 , 영상파일 열거면 이름 넣을것
        #fgbg = cv2.createBackgroundSubtractorMOG2()

        width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
        height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

        while(True):
            self.st_frame = self.st_frame + 1
            if self.st_frame != self.sz_frame:
                if self.st_frame % self.ob_frame != 0 and self.out_frame == 0:
                    continue
                if self.st_frame % 5 != 0:
                    continue

            # 영상처리
            ret, frame = cap.read()
            if frame is None: break;
            frgray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            kernel = np.ones((3, 3), np.float32) / 25
            dst = cv2.filter2D(frgray, -1, kernel)
            edges = cv2.Canny(dst, 50, 100)
            _, contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

            # moment이용 무게중심을 구함
            max_area = 0;
            ci = 0
            for i in range(len(contours)):
                cnt = contours[i]
                area = cv2.contourArea(cnt)
                if (area > max_area):
                    max_area = area
                    ci = i
            contours = contours[ci]
            mmt = cv2.moments(contours)
            if mmt['m00'] != 0:
                mx = int(mmt['m10'] / mmt['m00'])
                my = int(mmt['m01'] / mmt['m00'])

            # 세이프티존 생성
            if self.st_frame == self.sz_frame:
                for i in range(0, width):
                    for j in range(0, height):
                        if edges[j, i] == 0:
                            edges[j, i] = 255
                        else:
                            edges[j, i] = 0
                            self.my_contours.append([i, j])
                B = np.array(self.my_contours)
                sz_x, sz_y, sz_w, sz_h = cv2.boundingRect(B)

                # 세이프티존 크기 설정
                tmp_rx = sz_x
                tmp_ry = sz_y
                sz_x = tmp_rx + int((100 - self.sz_size) / 200 * sz_w)
                sz_y = tmp_ry + int((100 - self.sz_size) / 200 * sz_h)
                sz_w = self.sz_size / 100 * sz_w
                sz_h = self.sz_size / 100 * sz_h

            # 존이탈
            if self.out(mx, my, sz_x, sz_y, sz_w, sz_h) == 1:
                self.out_frame = self.out_frame + 1
            else:
                self.out_frame = 0
            if self.out_frame > 30:
                print("존이탈!!!!")
                self.mPush.insertMSG("비디오 스레드")
                self.out_frame = 0

            if self.st_frame > self.sz_frame:
                cv2.rectangle(frame, (int(mx), int(my)), (int(mx), int(my)), (0, 0, 255), 8)
                cv2.rectangle(frame, (int(sz_x), int(sz_y)), (int(sz_x + sz_w), int(sz_y + sz_h)), (0, 0, 255), 3)

            cv2.imshow('fgmask', frame)
            #cv2.imshow('frame', fgmask)
            #cv2.imshow('dst2', dst2)
            cv2.imshow('EDGES', edges)

            k = cv2.waitKey(30) & 0xff
            if k == 27:
                break
        cap.release()
        cv2.destroyAllWindows()
@HaebinKim HaebinKim added the bug Something isn't working label May 13, 2018
@HaebinKim HaebinKim self-assigned this May 13, 2018
@HaebinKim HaebinKim added info and removed bug Something isn't working labels May 16, 2018
@HaebinKim HaebinKim changed the title vi class vi class(10th) May 16, 2018
@kuj0210
Copy link
Owner

kuj0210 commented May 17, 2018

세이프존그리는 부분 함수화 해서 보존하고, 기본적으로 다음코드에는 세이프존 안그리고 그냥 데이처적으로만 처리ㄱㄱ

완전히 똑같게 따를 필요는 없으나 주요한건 메서드를 나누어서 run을 보았을때 함수이름만 보고도 이 vi클레스가 어떤식으로 동작하는가 알 수 있을정도로 직관적이고 간결하게 정리

@kuj0210
Copy link
Owner

kuj0210 commented May 17, 2018

이부분 init 쪽으로 넣어서 멤버로 처리할 것, openCamera 로 메서드화


        cap = cv2.VideoCapture('test2.mp4')  # 웹켐쓸거면인자 0 , 영상파일 열거면 이름 넣을것
        #fgbg = cv2.createBackgroundSubtractorMOG2()

        width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
        height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

@kuj0210
Copy link
Owner

kuj0210 commented May 17, 2018

##영역별 함수화, 등장 변수 모두다 init으로 넣어서 멤버관리할 것

영상처리 : getCapture

moment이용 무게중심을 구함 : getMoment

세이프티존 생성: getSaftyZone

세이프티존 크기 설정: setSaftyZoneSize

존이탈: checkSaftyZone

@kuj0210
Copy link
Owner

kuj0210 commented May 17, 2018

완성된 run의 모습


self.openCamera()
self.getMoment()
if first :
    self.getSafty()
if self.checkSaftyZon = self.BREAK_AWAY:
    self.mPush.insertMSG(self.MSG_BREAK_AWAY)

@HaebinKim HaebinKim changed the title vi class(10th) vi class(11th) May 18, 2018
@HaebinKim HaebinKim changed the title vi class(11th) vi class(12th) May 21, 2018
@HaebinKim HaebinKim changed the title vi class(12th) vi class(11th) May 21, 2018
@HaebinKim HaebinKim changed the title vi class(11th) vi class(11th) 18.05.21 수정 May 21, 2018
@HaebinKim HaebinKim changed the title vi class(11th) 18.05.21 수정 vi class(11th) May 21, 2018
@HaebinKim HaebinKim changed the title vi class(11th) vi class(12th) May 28, 2018
@HaebinKim HaebinKim changed the title vi class(12th) vi class(13th) May 28, 2018
@HaebinKim HaebinKim changed the title vi class(13th) vi class(14th) May 30, 2018
@HaebinKim
Copy link
Collaborator Author

HaebinKim commented Nov 6, 2018

    if os.path.isfile("./" + self.PICTURE_NAME):
        os.remove("./" + self.PICTURE_NAME)

Vi.zip

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants