Exemplo n.º 1
0
    def init_camera(self, verbose_flag):
        # Find Camera
        self.camera_path = liboCams.FindCamera('oCam')
        if self.camera_path is None:
            print "Cannot find DevPath : please connect Camera"
            return False

        # Instantiate Camera with Verbose for collecting data
        self.camera = liboCams.oCams(self.camera_path, verbose=1)
        # Collecting Data
        self.gathering_camera_data(self.camera)

        # Camera setting reassign (?)
        for i in range(len(self.camera_format_list)):
            self.camera.Set(self.camera_format_list[i])

        self.camera_name = self.camera.GetName()
        rospy.loginfo("Currently Connecting to Camera : " +
                      str(self.camera_name))

        # Mute Data Printing if verbose is false
        if verbose_flag is False:
            self.camera.Close()
            self.camera = liboCams.oCams(self.camera_path, verbose=0)

        # Start Camera instance !
        self.camera.Start()
Exemplo n.º 2
0
def initiallizeocam(printstat):  # 0 not print 1 print
    global allthreadbreak
    devpath = liboCams.FindCamera('oCam')
    if devpath is None:
        print 'Plese connect to camera'
        allthreadbreak = True
        exit()

    test = liboCams.oCams(devpath, verbose=1)

    if printstat == 1:
        print 'Format List'
        fmtlist = test.GetFormatList()
        for fmt in fmtlist:
            print '\t', fmt

        print 'Control List'
        ctrlist = test.GetControlList()
        for key in ctrlist:
            print '\t', key, '\tID:', ctrlist[key]

    test.Close()
    test = liboCams.oCams(devpath, verbose=0)
    test.Set(fmtlist[1])
    ##Description Format list indicate by number
    test.Start()

    #example code for camera control
    val = test.GetControl(ctrlist['Exposure (Absolute)'])
    test.SetControl(ctrlist['Exposure (Absolute)'], 370)  #586#200
    return test
Exemplo n.º 3
0
# /usr/bin/env python2

import liboCams
import cv2
import time
import sys
import numpy as np
#from matplotlib import pyplot as plt
import main_stereo

devpath = liboCams.FindCamera('oCam')
if devpath is None:
    exit()

test = liboCams.oCams(devpath, verbose=1)
fmtlist = test.GetFormatList()
ctrlist = test.GetControlList()
test.SetControl(10094850, 400)  # control exposure
test.Close()

test = liboCams.oCams(devpath, verbose=0)
test.Set(fmtlist[0])
name = test.GetName()
test.Start()

start_time = time.time()

frame_cnt = 0

while True:
Exemplo n.º 4
0
    def getImageOcamS(self, mode='on'):  # ocam으로 이미지 받기
        self.cur_time = time.strftime('%Y%m%d_%H%M%S')  # 현재 연/월/일 시간:분:초
        self.costomer_face_img = '/home/byu/byU_main/advertising_main/costomer_image/' + self.cur_time + '_' + self.cur_place + '.jpg'  #이미지를 시간, 장소로 저장, original image
        self.processing_img = '/home/byu/byU_main/advertising_main/processing_image/' + self.cur_time + '_' + self.cur_place + '_p.jpg'  # filltering image
        # 오캠 구동을 위한 준비 과정
        devpath = liboCams.FindCamera('oCam')
        if devpath is None:
            exit()

        test = liboCams.oCams(devpath, verbose=1)

        fmtlist = test.GetFormatList()
        ctrlist = test.GetControlList()
        test.Close()
        # 오캠 구동을 위한 준비 과정

        # 오캠으로 영상 받기.
        test = liboCams.oCams(devpath, verbose=0)
        test.Set(fmtlist[self.index])
        print 'SET', fmtlist[self.index]
        name = test.GetName()
        test.Start()

        start_time = time.time()
        stop_time = start_time + float(self.playtime)

        ##### 카메라로부터 이미지 받기 시작 ####

        frame_cnt = 0
        self.capture_result = False

        # 오캠으로 영상 받기.
        while True:
            if name == 'oCamS-1CGN-U':  # oCamS-1CGN-U 카메라일 경우
                self.capture_result = True  # 카메라로부터 이미지를 얻었다면 얻었다고 표시
                left_ = test.GetFrame(mode=2)  # 좌우 카메라 이미지 얻음.

                left_ = cv2.cvtColor(left_, cv2.COLOR_BAYER_GB2BGR)
                cv2.imwrite(self.costomer_face_img, left_)  # 좌측 이미지 저장
                if mode == 'on':
                    self.img_histequalize(
                        self.costomer_face_img,
                        self.processing_img)  # 히스토그램 평활화한 이미지 저장
            else:  # oCamS-1CGN-U 카메라가 아닐 경우
                print("Error Not oCamS-1CGN-U")

            char = cv2.waitKey(1)
            if char == 27:
                break
            if time.time() > stop_time:
                break
            frame_cnt += 1

        print 'Result Frame Per Second:', frame_cnt / (time.time() - start_time
                                                       )  #camera 구동 시간
        print('------------------------------------------------------')
        print('')

        test.Stop()
        cv2.destroyAllWindows()
        test.Close()
    def __init__(self, dir, textfile_name, annotate, format_num):

        # Find oCam to initialize
        devpath = liboCams.FindCamera('oCam')
        if devpath is None:
            print("oCam not Found")
            exit()

        # Initialize camera
        print("Initializing Camera")
        self.camera = liboCams.oCams(devpath, verbose=0)

        # Create image directory if needed or find the next image index
        self.dir = dir
        self.count = 0
        self.annotate = bool(annotate)
        textfile = textfile_name + ".dat"

        print("Saving images to directory: " + dir + "/")
        print("Using info file: " + textfile)

        fmtlist = self.camera.GetFormatList()

        if format_num < 0:
            print('Format List')

            for i, fmt in enumerate(fmtlist):
                print('\t', i, " ", fmt)

            selected_fmt = int(
                raw_input("Enter a number from the list above: "))

        else:
            selected_fmt = format_num

        self.camera.Set(fmtlist[selected_fmt])

        if not os.path.exists(dir):  # check this is a new directory
            if os.path.exists(textfile):  # check if the info file exists
                print(
                    "Error: New Directory being used with a pre-existing info file."
                )
                exit()
            else:
                # create directory and info file
                os.makedirs(dir)
                self.info_file = open(textfile, "a")

        else:
            if os.path.exists(textfile):  # check if the info file exists
                #open file and get the next index to label new pics
                self.info_file = open(textfile, "a")
                self.count = len(next(os.walk(dir))[2])
                print("Found", self.count, "existing images in the directory.")

            else:
                print(
                    "Error: Existing Directory being used with a new info file."
                )
                exit()

        self.cv_saved_image = None
        self.fully_annotated = False

        self.startx = 0
        self.starty = 0

        self.endx = 0
        self.endy = 0

        self.camera.Start()
Exemplo n.º 6
0
#! /usr/bin/env python3

import liboCams
import cv2
import time

devpath = liboCams.FindCamera('oCamS-1CGN-U')

if devpath is None:
  print ('oCam Device Not Found!')
  exit()

test = liboCams.oCams(devpath, verbose=0)

fmtlist = test.GetFormatList()
for fmt in fmtlist:
  print (fmt)

ctrlist = test.GetControlList()
for key in ctrlist:
  print (key, hex(ctrlist[key]))

test.SetControl(ctrlist[b'Gain'], 60)
test.SetControl(ctrlist[b'Exposure (Absolute)'],200)
test.Close()

if True:
  test = liboCams.oCams(devpath, verbose=0)

  test.Set(fmtlist[2])
  ctrllist = test.GetControlList()
Exemplo n.º 7
0
Arquivo: byu.py Projeto: kyg1552/ByU
def byu_robot_main():
    global face_cnt
    # 오캠 구동을 위한 준비 과정
    devpath = liboCams.FindCamera('oCam')
    if devpath is None:
        exit()

    test = liboCams.oCams(devpath, verbose=1)

    fmtlist = test.GetFormatList()
    ctrlist = test.GetControlList()
    test.Close()
    # 오캠 구동을 위한 준비 과정

    # 오캠으로 영상 받기.
    test = liboCams.oCams(devpath, verbose=0)
    test.Set(fmtlist[options.index])
    print 'SET', fmtlist[options.index]
    name = test.GetName()
    test.Start()

    start_time = time.time()
    stop_time = start_time + float(options.playtime)

    ##### 카메라로부터 이미지 받기 시작 ####
    costomer_face_img = './costomer_image/faceCapture' + str(
        face_cnt) + '.jpg'  #이미지를 번호 넘버링하면서 저장 가능
    left_img = './costomer_image/left_right_image/left_image' + str(
        face_cnt) + '.jpg'
    right_img = './costomer_image/left_right_image/right_image' + str(
        face_cnt) + '.jpg'

    frame_cnt = 0

    # 오캠으로 영상 받기.
    while True:
        if name == 'oCamS-1CGN-U':  # oCamS-1CGN-U 카메라일 경우
            capture_result = True  # 카메라로부터 이미지를 얻었다면 얻었다고 표시
            left_, right_ = test.GetFrame(mode=2)  # 좌우 카메라 이미지 얻음.

            left_ = cv2.cvtColor(left_, cv2.COLOR_BAYER_GB2BGR)
            cv2.imwrite(left_img, left_)  # 좌측 이미지 저장

            right_ = cv2.cvtColor(right_, cv2.COLOR_BAYER_GB2BGR)
            cv2.imwrite(right_img, right_)  #우측 이미지 저장

        else:  # oCamS-1CGN-U 카메라가 아닐 경우
            frame = test.GetFrame()
            rgb = cv2.cvtColor(frame, cv2.COLOR_YUV2BGR_YUYV)
            capture_result = True  # 카메라로부터 이미지를 얻었다면 얻었다고 표시

        char = cv2.waitKey(1)
        if char == 27:
            break
        if time.time() > stop_time:
            break
        frame_cnt += 1

    print 'Result Frame Per Second:', frame_cnt / (time.time() - start_time
                                                   )  #camera 구동 시간

    left = cv2.imread(left_img)
    right = cv2.imread(right_img)

    face_img = Image_Stitching().blending(left, right)

    cv2.imwrite(costomer_face_img, face_img)

    test.Stop()
    cv2.destroyAllWindows()
    test.Close()

    ##### 카메라로부터 이미지 받기 끝 ####

    ##### 이미지에서 얼굴을 찾아서 얼굴에서 특징(나이, 성별)추출 시작 ####
    if capture_result != False:  # 카메라가 정상적으로 동작한 경우
        #print("")

        img_url = costomer_face_img
        faces = CF.face.detect(img_url, True, False, 'age,gender')

        data = {}
        gender_data = []
        age_data = []
        gender_age = []
        people = 0

        male = np.zeros(
            8
        )  #남성 연령대 인원 수 0~9, 10~19, 20~29, 30~39, 40~49, 50~59, 60~69, 70~79, 80~89, 90~99
        female = np.zeros(
            8
        )  #여성 연령대 인원 수 0~9, 10~19, 20~29, 30~39, 40~49, 50~59, 60~69, 70~79, 80~89, 90~99

        for face in faces:
            add = []
            data = face['faceAttributes']
            #gender_data.append(data['gender']) # DB 저장 부분
            #age_data.append(data['age'])
            #data = {'age': age_data, 'gender': gender_data}
            add.append(data['gender'])
            add.append(data['age'])
            gender_age.append(add)
            people += 1

        people_check = 0  # 촬영한 사진에 얼굴이 있는지 판단하는 변수
        # 얼굴이 감지 안되면 0, 얼굴 감지 시 1

        for gender, age in gender_age:  # 남자,여자 각 연령대별 숫자 카운트
            if gender == 'male' and age >= 0 and age < 10:
                male[0] += 1
                people_check = 1
            elif gender == 'male' and age >= 10 and age < 20:
                male[1] += 1
                people_check = 1
            elif gender == 'male' and age >= 20 and age < 30:
                male[2] += 1
                people_check = 1
            elif gender == 'male' and age >= 30 and age < 40:
                male[3] += 1
                people_check = 1
            elif gender == 'male' and age >= 40 and age < 50:
                male[4] += 1
                people_check = 1
            elif gender == 'male' and age >= 50 and age < 60:
                male[5] += 1
                people_check = 1
            elif gender == 'male' and age >= 60 and age < 70:
                male[6] += 1
                people_check = 1
            elif gender == 'male' and age >= 70 and age < 80:
                male[7] += 1
                people_check = 1
            elif gender == 'male' and age >= 80 and age < 90:
                male[8] += 1
                people_check = 1
            elif gender == 'male' and age >= 90 and age < 100:
                male[9] += 1
                people_check = 1
            elif gender == 'female' and age >= 0 and age < 10:
                female[0] += 1
                people_check = 1
            elif gender == 'female' and age >= 10 and age < 20:
                female[1] += 1
                people_check = 1
            elif gender == 'female' and age >= 20 and age < 30:
                female[2] += 1
                people_check = 1
            elif gender == 'female' and age >= 30 and age < 40:
                female[3] += 1
                people_check = 1
            elif gender == 'female' and age >= 40 and age < 50:
                female[4] += 1
                people_check = 1
            elif gender == 'female' and age >= 50 and age < 60:
                female[5] += 1
                people_check = 1
            elif gender == 'female' and age >= 60 and age < 70:
                female[6] += 1
                people_check = 1
            elif gender == 'female' and age >= 70 and age < 80:
                female[7] += 1
                people_check = 1
            elif gender == 'female' and age >= 80 and age < 90:
                female[8] += 1
                people_check = 1
            elif gender == 'female' and age >= 90 and age < 100:
                female[9] += 1
                people_check = 1

        print("gender age set:")
        print(gender_age)
        print("people: %d" % (people))
        print("male 10~19: %d" % (male[1]))
        print("male 20~29: %d" % (male[2]))
        print("male 30~39: %d" % (male[3]))
        print("male 40~49: %d" % (male[4]))
        print("male 50~59: %d" % (male[5]))
        print("male 60~69: %d" % (male[6]))
        print("female 10~19: %d" % (female[1]))
        print("female 20~29: %d" % (female[2]))
        print("female 30~39: %d" % (female[3]))
        print("female 40~49: %d" % (female[4]))
        print("female 50~59: %d" % (female[5]))
        print("female 60~69: %d" % (female[6]))

        ##### 이미지에서 얼굴을 찾아서 얼굴에서 특징(나이, 성별)추출 시작 ####

        # Download the image from the url
        img = Image.open(img_url)

        # For each face returned use the face rectangle and draw a red box.
        draw = ImageDraw.Draw(img)
        k = 1
        for face in faces:  # 캡쳐한 이미지의 얼굴들 빨간색 사각형 밑 번호 표시
            draw.rectangle(getRectangle(face), outline='red')
            n = str(k)
            draw.text(getRectangleFont(face),
                      n,
                      font=None,
                      fill=(255, 255, 255, 255))
            k += 1

        # Display the image in the users default image browser.
        #img.show()
        ##### 이미지에서 얼굴을 찾아서 bounding box 끝 ####

        ##### 얼굴에서 추출된 정보를 이용하여 광고 추출 및 송출 시작 ####
        from moviepy.editor import *

        if people_check == 0:
            print("Not Detected Face!!")
        else:  # 카메라에 정상적으로 얼굴이 찍혔다면 광고 찾아서 실행
            male_max_index = male.argmax()
            female_max_index = female.argmax()
            if male[male_max_index] > female[female_max_index]:
                print("male: %d~%d" %
                      (male_max_index * 10, male_max_index * 10 + 9))
                if male_max_index == 1:
                    print("male video 10~")
                    video_file = './adv/male10.mp4'
                elif male_max_index == 2:
                    print("male video 20~")
                    video_file = './adv/male20.mp4'
                elif male_max_index == 3:
                    print("male video 30~")
                    video_file = './adv/male30.mp4'
                elif male_max_index == 4:
                    print("male video 40~")
                    video_file = './adv/male40.mp4'
                elif male_max_index == 5:
                    print("male video 50~")
                    video_file = './adv/male50.mp4'
                elif male_max_index == 6:
                    print("male video 60~")
                    video_file = './adv/male60.mp4'

                clip = VideoFileClip(video_file)
                clip.preview()

            else:
                print("female: %d~%d" %
                      (female_max_index * 10, female_max_index * 10 + 9))
                if female_max_index == 1:
                    print("female video 10~")
                    video_file = './adv/female10.mp4'
                elif female_max_index == 2:
                    print("female video 20~")
                    video_file = './adv/female20.mp4'
                elif female_max_index == 3:
                    print("female video 30~")
                    video_file = './adv/female30.mp4'
                elif female_max_index == 4:
                    print("female video 40~")
                    video_file = './adv/female40.mp4'
                elif female_max_index == 5:
                    print("female video 50~")
                    video_file = './adv/female50.mp4'
                elif female_max_index == 6:
                    print("female video 60~")
                    video_file = './adv/female60.mp4'

                clip = VideoFileClip(video_file)
                clip.preview()
                img.close()
                pygame.quit()
                ##### 얼굴에서 추출된 정보를 이용하여 광고 추출 및 송출 끝 ####
    else:  # 카메라가 정상적으로 동작 안한 경우
        print("error: No Face!! or No Camera!!")
        print("Please Check camera")

    face_cnt += 1