Пример #1
0
def main():
    mask = make_mask()

    src = Src(camera(mask))

    cv.imshow('-FACE-  continue-(Press eny key)',
              cv.resize(src.img, (540, 720)))
    cv.waitKey(0)
    cv.destroyAllWindows()

    # 中心判定
    detection(src)

    # 調節
    adjustment(src)

    print("left<y: {},  x: {}>,  right<y: {},  x: {}>".format(
        src.left.y, src.left.x, src.right.y, src.right.x))
    print("l_length: {},  r_length: {}".format(src.left.length,
                                               src.right.length))

    contact(src)

    # 拡大
    # img = cv.resize(src.result, (540, 720))
    # cv.imshow('-RESULT-  continue-(Press eny key)', img)

    # 通常
    cv.imshow('-RESULT-  continue-(Press eny key)', src.result)

    cv.waitKey(0)

    cv.imwrite("result.jpg", src.result)
def main():
    src = img_read()

    print("name: {}\n".format(src.name))

    # img_show('-FACE-    continue = (Press eny key)', cv.resize(src.img, (540, 720)))

    # 中心判定
    detection(src)

    # 調節
    adjustment(src)

    # コンタクト貼り付け
    contact(src)

    key = img_show(
        '-RESULT-    save = (Press < s >),  end = (Press other key)',
        cv.resize(src.result, (540, 720)))

    if key == ord('s') or key == ord('S'):
        cv.imwrite("result_" + src.name + ".jpg", src.result)
        print("\n保存しました")

    cv.destroyAllWindows()
def test_all(id):
    path = 'test/test_images'
    images = os.listdir(path)

    for image in images:
        detect = detection(path + '\\' + image, id)
        detect.make_detect_img()
Пример #4
0
 def get_frame(self):
     success, image = self.video.read()
     frame_rate = self.video.get(5)
     image, threshold = detection.detection(success, image)
     ret, jpeg = cv2.imencode('.jpg', image)
     ret2, jpeg2 = cv2.imencode('.jpg', threshold)
     return jpeg.tobytes(), jpeg2.tobytes()
Пример #5
0
def main():

    choix = int(
        input(
            "Choissisez 1. Pour l'enregistrement 2. Pour la reconnaissance du visage : "
        ))

    if choix == 1:
        print("Bienvenue dans le mode enregistrement")
        video_capture = cv2.VideoCapture(0)

        # appel de la fonction detection avec retour de l'image detecté
        face = detection(video_capture)
        #mise en forme de l'image
        nom = input("Nom de la personne : ")
        face = enregistrement(face, nom)
        #enregistrement de l'image
        #

    elif choix == 2:
        print("Bienvenue dans le mode reconnaissance")
        video_capture = cv2.VideoCapture(0)
        visage = compare(video_capture)

        # appel de la fonction detection avec retour de l'image detecté
        #face = detection()
        #mise en forme de l'image
        #face = format(face)
        #comparaison avec la base de donnée

    elif choix != 1 and choix != 2:
        choix = int(
            input(
                "Choissisez 1. Pour l'enregistrement 2. Pour la reconnaissance du visage : "
            ))
def pendu(liste, erreur, mot):
    er_max = 8
    lettre = liste[len(liste) - 1]
    if (d.detection(lettre, mot) == False):
        erreur = erreur + 1
    nouv_mot = a.affichage(liste, mot)
    print(nouv_mot)
    victoire = v.win(nouv_mot)
    return erreur
Пример #7
0
 def post(self):
     url = self.request.body
     face_id_emotion_dict, face_id_eye_open_dict = detection.detection(url)
     # print face_id_emotion_dict, face_id_eye_open_dict
     eye_close_id_list = [
         id for id in face_id_eye_open_dict.keys()
         if not face_id_eye_open_dict[id]
     ]
     # print eye_close_id_list
     sleep_ones = []
     for id in eye_close_id_list:
         for known_face_id in face_id_name_dict.keys():
             if verification.verification(id, known_face_id):
                 sleep_ones.append(face_id_name_dict[known_face_id])
     db.execute("""INSERT INTO log(ts, names) VALUES(UTC_TIMESTAMP, %s)""",
                ",".join(sleep_ones))
     self.write({"id": sleep_ones})
    def get_bounding_box(self, img, vis=True):
        '''
            Find the bounding box of the stop sign
            call other functions in this class if needed
            
            Inputs:
                img - original image
            Outputs:
                boxes - a list of lists of bounding boxes. Each nested list is a bounding box in the form of [x1, y1, x2, y2] 
                where (x1, y1) and (x2, y2) are the top left and bottom right coordinate respectively. The order of bounding boxes in the list
                is from left to right in the image.
                
            Our solution uses xy-coordinate instead of rc-coordinate. More information: http://scikit-image.org/docs/dev/user_guide/numpy_images.html#coordinate-conventions
        '''
        mask_img = self.segment_image(img)
        # dfs to union patches
        bitmaps = detection(mask_img)
        boxes = []
        for patch in bitmaps:
            bitmap = patch[0]
            for region in regionprops(bitmap.astype(np.int)):
                # skip small images
                if region['Area'] < threshold:
                    continue
                # fit poly to make sure the shape is desirable

                # draw rectangle around segmented coins
                if vis:
                    fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(6, 6))
                    ax.imshow(bitmap.astype(np.float), cmap='gray')
                    minr, minc, maxr, maxc = region['BoundingBox']
                    rect = mpatches.Rectangle((minc, minr),
                                              maxc - minc,
                                              maxr - minr,
                                              fill=False,
                                              edgecolor='red',
                                              linewidth=2)
                    ax.add_patch(rect)
                    plt.show()
                boxes.append((minc, minr, maxc, maxr))
        return boxes
Пример #9
0
    n_iter = box_iter.get()
    print(n_iter)
    training_set = date_set()
    error = recognit.new(training_set, n_iter)
    plt.plot(error)
    plt.show()
    recognit.save()


def load(recognit):
    recognit.load()


main = Tkinter.Tk()
root = Tkinter.Toplevel(main)
recognit = detection([28, 28], 0.0001, 0.1, root, [784, 784], "model")

box_iter = Tkinter.Entry(main, width=40)
box_iter.grid(row=0, column=1)
box_iter.insert(0, "please insert the number of interactions")

botton_new = Tkinter.Button(main,
                            command=lambda: new(recognit, box_iter),
                            text="NEW")
botton_new.grid(row=0, column=0)

botton_load = Tkinter.Button(main, command=lambda: load(recognit), text="LOAD")
botton_load.grid(row=2, column=0)

main.mainloop()
Пример #10
0
def cv(buf):
    start = time.time()
    pic = 0
    pic_smlie = 0
    smile = 0
    result = []
    try:
        face_cascade = cv2.CascadeClassifier(
            "/home/pi/Desktop/project/haarcascade_frontalface_default.xml")
        face2_cascade = cv2.CascadeClassifier(
            "/home/pi/Desktop/project/lbpcascade_frontalface.xml")
        lefteye_cascade = cv2.CascadeClassifier(
            "/home/pi/Desktop/project/haarcascade_mcs_lefteye.xml")
        righteye_cascade = cv2.CascadeClassifier(
            "/home/pi/Desktop/project/haarcascade_mcs_righteye.xml")
        smile_cascade = cv2.CascadeClassifier(
            "/home/pi/Desktop/project/haarcascade_smile.xml")
    except:
        print("검출기 예러 ")
        exit(0)

    os.system('sudo modprobe bcm2835-v4l2')
    cap = cv2.VideoCapture(0)
    cap.set(3, 480)
    cap.set(4, 640)

    while True:
        set_image = 0
        ret, frame = cap.read()
        if not ret:
            print(' video error')
            break

        #frame=cv2.imread("./picture/2.jpg");
        result_img = np.zeros((320, 240))
        vision_image = frame[0:640, 0:480]
        #grayimage=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
        #image=cv2.resize(frame,None,1,1,cv2.INTER_LINEAR)

        set_image, result_img = detection.detection(
            frame, result_img, face_cascade, face2_cascade, lefteye_cascade,
            righteye_cascade, smile_cascade)
        if set_image == 1:
            pic = pic + 1
            cv2.imwrite("./buf/set.png", vision_image)
            result.append(result_img)
            #result.append(frame)
        elif set_image == 2:
            pic = pic + 1
            pic_smlie = pic_smlie + 1
            cv2.imwrite("./buf/set.png", vision_image)
            result.append(result_img)
            #result.append()

        cv2.imshow('image', frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

        end = time.time()
        #print(end-start)
        if (((end - start) > 20.0) or (pic == 5)):
            for i in range(pic):
                paths = "./buf/%d.png" % i
                cv2.imwrite(paths, result[i])
            """
            if pic>0:
                s= socket.socket(socket.AF_INET,socket.SOCK_STREAM)
                s.connect((HOST,PORT))
                s.send(("pipic@@"+str(pic)+"@").encode())
                msg=s.recv(4).decode()
                if (msg==str(1)):
                    for i in range(pic):
                        paths="./buf/%d.png" %i
                        #cv2.imwrite(paths,result[i])
                        s_i=open(paths,'rb')

                        size=os.path.getsize(paths)
                        send_size=int(size/2048)
                        for j in range(send_size+1):
                            byte=s_i.read(2048)
                            print(byte)
                            s.send(byte)

                        #s.send(("@@").encode())
                        #encode_param=[int(cv2.IMWRITE_JPEG_QUALITY),90]
                        #res,imgencode=cv2.imencode('.jpg',send_image,encode_param)
                        #date=np.array(imgencode)
                        #stringdata=date.tostring()
                        msg=s.recv(4).decode()
                        
                elif(msg==str(-1)):
                    print("socket error")
                s.close();
                print(str(end-start))
                #cancel.cancel(pic,pic_smlie)
        """
            #vision_image=cv2.imread("./buf/set.png");

            vision_smile = vision.main("1")
            if ((vision_smile == 'POSSIBLE') or (vision_smile == 'LIKELY')
                    or (vision_smile == 'VERY_LIKELY')):
                print(vision_smile)
                smile = 1
            else:
                smile = 0

            break
    cancel.cancel(pic, smile)
    cap.release()
    cv2.waitKey(100)
    cv2.destroyAllWindows()
    cv2.waitKey(1)
    #print(1)
    return pic, pic_smlie, smile
Пример #11
0
from detection import detection
import cv2

det = detection()

while True:
    dst = det.object_detection()
    det._test_camera()
    
    k = cv2.waitKey(1)
    if k == 13:
        break
Пример #12
0
        input = np.loadtxt('./log/pcm.csv',
                           delimiter=';',
                           dtype=np.float32,
                           skiprows=2 + cur_line,
                           usecols=range(2, 12))
        if sys.getsizeof(input[0]) > 30:
            input = input[len(input) - 1]

        #print(input, cur_line) #for testing.
        cur_line = cur_line + 1
        time.sleep(0.5)

        input_func = []
        input_func.append(input)

        result = dtt.detection(input_func)  #run detection code.
        print(result, cur_line)
        if result and pr_flag:
            if pr_flag:
                print("\n\t  -----------------  ")
                print("\t!                   !")
                print("\t!  Attack Detected! !")
                print("\t!                   !")
                print("\t  ------------- ")
                pr_flag = 0
        elif not result and not pr_flag:
            pr_flag = 1

        if cur_line is 20:
            f = open('./log/pcm.csv', 'r+')
            f.truncate()
image = [cv.imread(address + imagelist[i]) for i in range(len(imagelist))]
image_mask = [
    Image.open(address + imagelist[i]).convert("RGB")
    for i in range(len(imagelist))
]

stage_1_input_dir = ""
mask_dir = ""
gpu1 = 0
input_opts_stage1 = [
    "--test_path", stage_1_input_dir, "--output_dir", mask_dir, "--input_size",
    "scale_256", "--GPU", gpu1
]

os.chdir("./Global")
_, mask = detection.detection(input_opts_stage1, image_mask, imagelist)
os.chdir("../")

if not os.path.exists(final_address):
    os.makedirs(final_address)

for i in range(len(image)):
    prev = -1
    next = 0
    chosen = -1
    #   print("* frame "+str(i)+" *")
    if i == 0:
        next = getPSNR(image[i], image[i + 1])
        chosen = (next, i + 1)
        # print(getPSNR(image[i], image[i+1]))
        # print("**")
Пример #14
0
def train():
    model = LogisticRegression((4, 1))
    dataloader = DataLoader()
    dataloader.train_validation_test_split()
    train_X, train_Y = dataloader.get_train()
    val_X, val_Y = dataloader.get_validation()
    test_X, test_Y = dataloader.get_test()
    return train_X, train_Y


from detection import detection, shape_similarity
import argparse

if __name__ == "__main__":

    # model = train()
    train_X, train_Y = train()
    gnb = GaussianNB()
    test_img = np.array(Image.open('trainset/10.jpg'))
    test_X = test_img.reshape(-1, 3)
    y = gnb.fit(train_X, train_Y).predict(test_X)

    #transform(np.array(test_img), model = LogisticRegression((4,1)))
    plt.imshow(y.reshape(test_img.shape[:2]), cmap='gray')
    plt.show()
    mask = y.reshape(test_img.shape[:2])
    bitmap = detection(mask)
    #    from skimage.measure import find_countour
    shape_similarity(mask)
Пример #15
0
# wn.split_pipe('%s' % leak, '%s_b' % leak, '%s_leak_node' % leak)
# leak_node = wn.get_node('%s_leak_node' % leak)
# leak_node.add_leak(wn, area=0.15, start_time=leak_start_time, end_time=4*3600)
# ln=wn.get_node("%s_leak_node" % leak)

while (i <= simulation_time / 1800):
    for l in leaks:
        ln = wn.get_node("%s_leak_node" % l.name)
        if i == l.start_time / 1800:
            ln.leak_status = True

    wn.options.time.duration = 1800 * (i + 1)
    res = sim.run_sim()
    to_close.append(
        detection.detection(wn, res, i, nodes_names, pipes_names, pipes_length,
                            link_controls))
    closed = detection.close(wn, to_close, i, link_controls, max_distance,
                             teams, closed)
    j = detection.open(wn, closed, i, open_link_controls, j, sources)
    Data_base.update_db(wn, res, i)
    CHEM = res.node['quality'].loc[wn.options.time.duration, :]
    STAT = res.link["status"].loc[wn.options.time.duration, :]
    VEL = res.link["velocity"].loc[wn.options.time.duration, :]
    wntr.graphics.plot_network(wn,
                               node_attribute=CHEM,
                               link_attribute=STAT,
                               node_size=20,
                               link_range=[0, 1],
                               node_range=[0, 1000],
                               title='Chemical concentration at time: %s' %
                               wn.options.time.duration)
Пример #16
0
# USAGE
#python main.py --shape-predictor shape_predictor_68_face_landmarks.dat

# import the necessary packages

from dir import directory
from detection import detection
import os, fnmatch
import numpy as np

p = '/home/ozaki/Downloads/facial-landmarks'
files = os.listdir(p)
ext = "*.avi"
path = []

path, csv_names = directory(p, files)
counter = np.size(path)
detection(counter, path, csv_names)
Пример #17
0
while restart == "r":
    victoire = False
    erreur = 0
    mot = r.mot_random(mots)
    print("Vous jouer aux jeux du pendu.")
    while erreur < er_max and victoire == False:
        print("Donner une lettre.")
        nouv_mot = a.affichage(liste, mot, True)
        print("vous avez deja essayer les lettre ", liste)
        lettre = input()
        while lettre in liste:
            print("vous avez deja taper ce chiffre taper en un autre.")
            lettre = input()
        liste.append(lettre)
        if (d.detection(lettre, mot)):
            print("la lettre existe dans le mot donner.")
        else:
            print("la lettre n'existe pas dans le mot donner.")
            erreur = erreur + 1
        print("il vous reste ", er_max - erreur, " erreur aux total.")
        nouv_mot = a.affichage(liste, mot, False)
        print(nouv_mot)
        victoire = v.win(nouv_mot)

    if higt_score < er_max - erreur:
        higt_score = er_max - erreur
        print("vous avez battu votre ancine Hight_score le nouveaux est de ",
              higt_score)
    else:
        print("votre ancient higt-score et de  ", higt_score)
 def get_frame_threshold(self):
     success, image = self.video.read()
     image, threshold = detection.detection(success, image)
     ret, jpeg = cv2.imencode('.jpg', threshold)
     return jpeg.tobytes()
Пример #19
0
                                    input_names)

    else:
        mask_dir = os.path.join(stage_1_output_dir, "masks")
        new_input = os.path.join(mask_dir, "input")
        new_mask = os.path.join(mask_dir, "mask")

        # input_opts_stage1_command1 = ["--test_path", stage_1_input_dir, "--output_dir", mask_dir,
        #                             "--input_size", "full_size", "--GPU", gpu1]

        input_opts_stage1_command1 = [
            "--test_path", stage_1_input_dir, "--output_dir", mask_dir,
            "--input_size", "scale_256", "--GPU", gpu1
        ]

        input_imgs_after_detection, mask_dirs = detection.detection(
            input_opts_stage1_command1, input_images, input_names)

        # input_opts_stage1_command2 = ["--Scratch_and_Quality_restore", "--test_input", new_input,
        #                             "--test_mask", new_mask, "--outputs_dir", stage_1_output_dir,
        #                             "--gpu_ids", gpu1]

        input_opts_stage1_command2 = [
            "--test_mode", "Scale", "--Scratch_and_Quality_restore",
            "--test_input", new_input, "--test_mask", new_mask,
            "--outputs_dir", stage_1_output_dir, "--gpu_ids", gpu1
        ]

        restored_images = test.test(input_opts_stage1_command2,
                                    input_imgs_after_detection,
                                    input_names,
                                    mask_loader=mask_dirs)
Пример #20
0
    if not opts.with_scratch:
        input_opts_stage1 = ["--test_mode", "Full", "--Quality_restore", 
                            "--test_input", stage_1_input_dir, "--outputs_dir", stage_1_output_dir, 
                            "--gpu_ids", gpu1]
    
        test.test(input_opts_stage1)
    
    else:
        mask_dir = os.path.join(stage_1_output_dir, "masks")
        new_input = os.path.join(mask_dir, "input")
        new_mask = os.path.join(mask_dir, "mask")
        
        input_opts_stage1_command1 = ["--test_path", stage_1_input_dir, "--output_dir", mask_dir,
                                    "--input_size", "full_size"]
        detection.detection(input_opts_stage1_command1, input_images, input_names)
        
        input_opts_stage1_command2 = ["--Scratch_and_Quality_restore", "--test_input", new_input,
                                    "--test_mask", new_mask, "--outputs_dir", stage_1_output_dir]
        
        test.test(input_opts_stage1_command2)

    ## Solve the case when there is no face in the old photo
    stage_1_results = os.path.join(stage_1_output_dir, "restored_image")
    stage_4_output_dir = os.path.join(opts.output_folder, "final_output")
    if not os.path.exists(stage_4_output_dir):
        os.makedirs(stage_4_output_dir)
    for x in os.listdir(stage_1_results):
        img_dir = os.path.join(stage_1_results, x)
        shutil.copy(img_dir, stage_4_output_dir)
#info of each templates
#detection should return
#
#the (row,col) list in tmp_idx
#
#confidence values
#which can be calculated using the denominator
#by comparing each template to each other
#
#template size
#which is the size of template after scaling
#
#Also, the functions will draw the corresponding boxes

tmp1_idx, tmp1_conf, tmp1_size = detection(scaled_img_bw, draw, "template_1")
#print("tmp1 finished!\n")
tmp2_idx, tmp2_conf, tmp2_size = detection(scaled_img_bw, draw, "template_2")
#print("tmp2 finished!\n")
tmp3_idx, tmp3_conf, tmp3_size = detection(scaled_img, draw, "template_3")
#print("tmp3 finished!\n")
tmp4_idx, tmp4_conf, tmp4_size = detection(scaled_img, draw, "template_4")
#print("tmp4 finished!\n")

#rescaling the coordinates
#and size of the templates
tmp1_idx = [(int(tmp1_idx[i][0] / img_scale), int(tmp1_idx[i][1] / img_scale))
            for i in range(len(tmp1_idx))]
tmp1_size = (int(tmp1_size[0] / img_scale), int(tmp1_size[1] / img_scale))
tmp2_idx = [(int(tmp2_idx[i][0] / img_scale), int(tmp2_idx[i][1] / img_scale))
            for i in range(len(tmp2_idx))]
Пример #22
0
    return


# Main Loop
if __name__ == '__main__':

    # warm up display
    for i in range(5):
        print("--- TEST DISPLAY {} ---".format(i))
        img = cv2.imread(PLEASE_SCAN_FILE_PATH)
        display_scanned_item2(img)
        sleep(3)

    #初期化 モジュールのインスタを作る
    #c_detect = dummy_detection.DummyDetection(False)
    c_detect = detection.detection()
    #c_predict = dummy_prediction.DummyPrediction(False)
    c_predict = prediction.prediction(n_category=5, threshold=0.95)
    #c_predict2 = dummy_prediction2.DummyPrediction2(False)
    c_predict2 = classify_products()
    c_predict2.preprocessing()

    #Display.pyを起動させる
    #res = subprocess.check_call('clear')

    print("\n\n----------- START -----------\n\n")

    #Main loop
    while True:
        #検出部
        #scanned_image, padded_image, image_w_bounding = c_detect.object_detection()