Ejemplo n.º 1
0
def merge_images_in_folders(path_input1,
                            path_input2,
                            path_output,
                            mask='*.png,*.jpg',
                            rotate_first=False):
    tools_IO.remove_files(path_output, create=True)

    fileslist1 = tools_IO.get_filenames(path_input1, mask)
    fileslist2 = tools_IO.get_filenames(path_input2, mask)

    fileslist1.sort()
    fileslist2.sort()

    for filename1, filename2 in zip(fileslist1, fileslist2):
        image1 = cv2.imread(path_input1 + filename1)
        image2 = cv2.imread(path_input2 + filename2)
        if image1 is None or image2 is None: continue

        if rotate_first:
            image1 = numpy.transpose(image1, [1, 0, 2])

        shape1 = image1.shape
        shape2 = image2.shape

        image2_resized = cv2.resize(
            image2, (int(shape1[0] * shape2[1] / shape2[0]), shape1[0]))
        image = numpy.zeros(
            (shape1[0], shape1[1] + image2_resized.shape[1], shape1[2]),
            dtype=numpy.uint8)

        image[:, :shape1[1]] = tools_image.desaturate(image1)
        image[:, shape1[1]:] = image2_resized
        cv2.imwrite(path_output + filename1, image)

    return
Ejemplo n.º 2
0
def merge_images_in_folders_temp(path_input1,
                                 path_input2,
                                 path_output,
                                 mask='*.png,*.jpg'):
    tools_IO.remove_files(path_output, create=True)

    fileslist1 = tools_IO.get_filenames(path_input1, mask)
    fileslist2 = tools_IO.get_filenames(path_input2, mask)

    fileslist1.sort()
    fileslist2.sort()

    for filename1, filename2 in zip(fileslist1, fileslist2):
        image1 = cv2.imread(path_input1 + filename1)
        image2 = cv2.imread(path_input2 + filename2)
        if image1 is None or image2 is None: continue

        image1 = cv2.resize(image1, (640, 320))
        image2 = cv2.resize(image2, (640, 320))
        red = 0 * image2.copy()
        red[:, :, 2] = 255

        weight = image2.copy() / 255

        image = cv2.add(image1 * (1 - weight), red * (weight))

        cv2.imwrite(path_output + filename1, image)

    return


# ---------------------------------------------------------------------------------------------------------------------
Ejemplo n.º 3
0
def example_calibrate_folder(folder_in, folder_out,marker_length_mm = 3.75, marker_space_mm = 0.5,dct = aruco.DICT_6X6_1000):
    tools_IO.remove_files(folder_out)

    num_cols, num_rows = 4, 5
    board = aruco.GridBoard_create(num_cols, num_rows, marker_length_mm, marker_space_mm,aruco.getPredefinedDictionary(dct))
    filenames = numpy.unique(tools_IO.get_filenames(folder_in, '*.jpg,*.png'))[:3]

    counter, corners_list, id_list, first = [], [], [], True
    for filename_in in filenames:
        base_name, ext = filename_in.split('/')[-1].split('.')[0], filename_in.split('/')[-1].split('.')[1]
        image = cv2.imread(folder_in + filename_in)
        img_gray = cv2.cvtColor(image,cv2.COLOR_RGB2GRAY)
        corners, ids, rejectedImgPoints = aruco.detectMarkers(img_gray, aruco.getPredefinedDictionary(dct))
        if first == True:
            corners_list = corners
            id_list = ids
            first = False
        else:
            corners_list = numpy.vstack((corners_list, corners))
            id_list = numpy.vstack((id_list,ids))
        counter.append(len(ids))

        image_temp = tools_image.desaturate(image.copy())
        aruco.drawDetectedMarkers(image_temp, corners)
        cv2.imwrite(folder_out+base_name+'.png',image_temp)
        print(base_name)


    counter = numpy.array(counter)
    ret, camera_matrix, dist, rvecs, tvecs = aruco.calibrateCameraAruco(corners_list, id_list, counter, board, img_gray.shape, None, None )

    print(camera_matrix)

    return
Ejemplo n.º 4
0
    def process_folder_extract_landmarks(self,folder_in, folder_out, write_images=True, write_annotation=True, delim='\t'):

        tools_IO.remove_files(folder_out, create=True)
        local_filenames = tools_IO.get_filenames(folder_in, '*.jpg')

        if write_annotation:
            myfile = open(folder_out+"Landmarks.txt", "w")
            myfile.close()

        for local_filename in local_filenames:

            image = cv2.imread(folder_in + local_filename)
            L_actor = self.D.get_landmarks(image)

            if write_images:
                del_triangles_A = Delaunay(L_actor).vertices
                result = self.D.draw_landmarks_v2(image, L_actor, color=(0, 192, 255),del_triangles=del_triangles_A)
                cv2.imwrite(folder_out + local_filename, result)

            if write_annotation:
                myfile = open(folder_out + "Landmarks.txt", "a")
                data = numpy.vstack((numpy.array([local_filename, local_filename]),(L_actor).astype(numpy.chararray))).T
                numpy.savetxt(myfile,data.astype(numpy.str),fmt='%s',encoding='str',delimiter=delim)
                myfile.close()

            print(local_filename)
        return
Ejemplo n.º 5
0
def example_homography_video(filename_target, folder_in, folder_out):

    tools_IO.remove_files(folder_out, create=True)

    im_target = cv2.imread(filename_target)
    p_target = numpy.array([[62, 48], [225, 48], [225, 93], [62, 93]])

    mask = numpy.where(im_target == (0, 0, 255))

    filenames = tools_IO.get_filenames(folder_in, '*.jpg')
    im_source = cv2.imread(folder_in + filenames[0])
    pad = 0
    p_source = numpy.array(
        [[0 + pad, 0 + pad], [im_source.shape[1] - pad, pad],
         [im_source.shape[1] - pad, im_source.shape[0] - pad],
         [pad, im_source.shape[0] - pad]],
        dtype=numpy.float)

    for filename_in in filenames:
        im_source = cv2.imread(folder_in + filename_in)

        homography2, status = tools_pr_geom.fit_homography(
            p_source.reshape((-1, 1, 2)), p_target.reshape((-1, 1, 2)))
        image_trans = cv2.warpPerspective(
            im_source, homography2, (im_target.shape[1], im_target.shape[0]))
        image_trans2 = numpy.zeros_like(image_trans)
        image_trans2[mask] = image_trans[mask]

        result = tools_image.put_layer_on_image(im_target,
                                                image_trans2,
                                                background_color=(0, 0, 0))
        cv2.imwrite(folder_out + filename_in, result)

    return
Ejemplo n.º 6
0
def get_images(folder_in, H, W):
    images = []
    for filename in tools_IO.get_filenames(folder_in, '*.jpg'):
        image = cv2.imread(folder_in + filename)
        image = tools_image.smart_resize(image, H, W)
        images.append(image)

    return numpy.array(images)
Ejemplo n.º 7
0
def process_folder_images(folder_in, folder_out):

    #tools_IO.remove_files(folder_out,create=True)
    filenames = tools_IO.get_filenames(folder_in, '*.jpg')

    for filename in filenames[:1]:
        P.process_file_granules(folder_in + filename, do_debug=True)

    return
Ejemplo n.º 8
0
    def generate_features(self,
                          path_input,
                          path_output,
                          limit=1000000,
                          mask='*.png,*.jpg'):

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

        dict_last_layers, dict_bottlenects = self.__last_full_layers4()

        outputs = [
            self.model.layers[len(self.model.layers) + i].output
            for i in dict_bottlenects.values()
        ]
        patterns = numpy.sort(
            numpy.array([
                f.path[len(path_input):] for f in os.scandir(path_input)
                if f.is_dir()
            ]))

        for each in patterns:
            print(each)
            local_filenames = tools_IO.get_filenames(path_input + each,
                                                     mask)[:limit]
            feature_filename = path_output + '/' + each + '_' + self.name + '.txt'
            features, filenames = [], []

            if not os.path.isfile(feature_filename):
                bar = progressbar.ProgressBar(max_value=len(local_filenames))
                for b, local_filename in enumerate(local_filenames):
                    bar.update(b)
                    image = cv2.imread(path_input + each + '/' +
                                       local_filename)
                    if image is None: continue
                    image_resized = tools_image.smart_resize(
                        image, self.input_image_size[0],
                        self.input_image_size[1])
                    image_resized = numpy.expand_dims(image_resized / 255.0,
                                                      axis=0)
                    bottlenecks = Model(self.model.input,
                                        outputs).predict(image_resized)
                    feature = numpy.hstack(
                        (bottlenecks[0].flatten(), bottlenecks[1].flatten()))

                    features.append(feature[0])
                    filenames.append(local_filename)

                features = numpy.array(features)

                mat = numpy.zeros((features.shape[0],
                                   features.shape[1] + 1)).astype(numpy.str)
                mat[:, 0] = filenames
                mat[:, 1:] = features
                tools_IO.save_mat(mat, feature_filename, fmt='%s', delim='\t')

        return
Ejemplo n.º 9
0
    def get_data_train(self, folder_in):

        local_filenames_data = tools_IO.get_filenames(folder_in,'*.jpg')
        local_filenames_mask = tools_IO.get_filenames(folder_in,'*.png')

        X_train, Y_train = [],[]

        for file_data,file_mask in zip (local_filenames_data,local_filenames_mask):
            image_data = cv2.imread(folder_in+file_data)
            image_mask = cv2.imread(folder_in + file_mask)

            image_data,image_mask = self.do_resize(image_data,image_mask)

            X_train.append(image_data)
            Y_train.append(numpy.array([image_mask[:,:,0]])/255)

        X_train = numpy.array(X_train)
        Y_train = numpy.array(Y_train)

        return X_train, Y_train
Ejemplo n.º 10
0
    def stage_data(self, folder_out):
        filenames = tools_IO.get_filenames(folder_out, 'screenshot*.png')
        ids = [(f.split('.')[0]).split('_')[1] for f in filenames]
        if len(ids) > 0:
            i = 1 + numpy.array(ids, dtype=int).max()
        else:
            i = 0

        cv2.imwrite(folder_out + 'screenshot_%03d.png' % i,
                    self.get_image(do_debug=True))

        return
Ejemplo n.º 11
0
    def generate_features(self,
                          path_input,
                          path_output,
                          limit=1000000,
                          mask='*.png,*.jpg'):

        init = tf.global_variables_initializer()
        sess = tf.Session()
        sess.run(init)

        if not os.path.exists(path_output):
            os.makedirs(path_output)
        #else:
        #tools_IO.remove_files(path_output)

        patterns = numpy.sort(
            numpy.array([
                f.path[len(path_input):] for f in os.scandir(path_input)
                if f.is_dir()
            ]))

        for each in patterns:
            print(each)
            local_filenames = tools_IO.get_filenames(path_input + each,
                                                     mask)[:limit]
            feature_filename = path_output + '/' + each + '_' + self.name + '.txt'
            features, filenames = [], []

            if not os.path.isfile(feature_filename):
                bar = progressbar.ProgressBar(max_value=len(local_filenames))
                for b, local_filename in enumerate(local_filenames):
                    bar.update(b)
                    image = cv2.imread(path_input + each + '/' +
                                       local_filename)
                    if image is None: continue
                    image = cv2.resize(
                        image, (self.input_shape[0], self.input_shape[1]))

                    feature = sess.run(self.fc7, feed_dict={self.x: [image]})

                    features.append(feature[0])
                    filenames.append(local_filename)

                features = numpy.array(features)

                mat = numpy.zeros((features.shape[0],
                                   features.shape[1] + 1)).astype(numpy.str)
                mat[:, 0] = filenames
                mat[:, 1:] = features
                tools_IO.save_mat(mat, feature_filename, fmt='%s', delim='\t')

        sess.close()
        return
Ejemplo n.º 12
0
    def generate_features(self,
                          path_input,
                          path_output,
                          mask='*.png',
                          limit=1000000):

        if not os.path.exists(path_output):
            os.makedirs(path_output)
        else:
            tools_IO.remove_files(path_output)
            tools_IO.remove_folders(path_output)

        patterns = numpy.sort(
            numpy.array([
                f.path[len(path_input):] for f in os.scandir(path_input)
                if f.is_dir()
            ]))

        for each in patterns:
            print(each)
            local_filenames = tools_IO.get_filenames(path_input + each,
                                                     mask)[:limit]
            feature_filename = path_output + '/' + each + '_' + self.name + '.txt'
            features, filenames = [], []

            if not os.path.isfile(feature_filename):
                bar = progressbar.ProgressBar(max_value=len(local_filenames))
                for b, local_filename in enumerate(local_filenames):
                    bar.update(b)
                    img = cv2.imread(path_input + each + '/' + local_filename)
                    if img is None: continue
                    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
                    img = cv2.resize(img,
                                     self.input_shape).astype(numpy.float32)
                    model = Model(inputs=self.model.input,
                                  outputs=self.model.get_layer(
                                      'global_average_pooling2d_1').output)
                    feature = model.predict(
                        preprocess_input(numpy.array([img])))[0]
                    features.append(feature)
                    filenames.append(local_filename)

                features = numpy.array(features)

                mat = numpy.zeros((features.shape[0],
                                   features.shape[1] + 1)).astype(numpy.str)
                mat[:, 0] = filenames
                mat[:, 1:] = features
                tools_IO.save_mat(mat, feature_filename, fmt='%s', delim='\t')

        return
Ejemplo n.º 13
0
def stage_faces_from_cam(folder_out):

    filenames = tools_IO.get_filenames(folder_out,'*.jpg')
    if len(filenames)>0:
        filenames.sort()
        idx = int(filenames[-1].split('.')[0])
    else:
        idx =0

    r1, r2 = 0,0
    use_camera = True
    cnt, start_time, fps = 0, time.time(), 0

    cap = cv2.VideoCapture(0)
    cap.set(3, camera_W)
    cap.set(4, camera_H)
    while (True):
        if use_camera:
            ret, image = cap.read()
            L = D.get_landmarks(image)
            if D.are_landmarks_valid(L):
                result = D.cut_face(image, L, target_W=camera_W, target_H=camera_H)
                L = D.get_landmarks(result)
                if D.are_landmarks_valid(L):
                    rotv, tvecs = D.get_pose(image,L)
                    rotv = rotv.reshape(3, 1)
                    tvecs = tvecs.reshape(3, 1)

                    rotMat, jacobian = cv2.Rodrigues(rotv)
                    r1,r2,r3= tools_calibrate.rotationMatrixToEulerAngles(rotMat)

                    cv2.imwrite(folder_out+'%06d_%1.2d_%1.2f.jpg'%(idx,r1,r2),result)
                    idx = idx + 1
            else:

                result = image.copy()

        if time.time() > start_time: fps = cnt / (time.time() - start_time)
        result = cv2.putText(result, '{0: 1.1f} {1}'.format(fps, ' fps'), (0, 15), cv2.FONT_HERSHEY_SIMPLEX, 0.4,(0, 0, 0), 1, cv2.LINE_AA)
        result = cv2.putText(result, '{0: 1.2f} {1: 1.2f}'.format(r1,r2), (0, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.4,(0, 0, 0), 1, cv2.LINE_AA)

        cv2.imshow('frame', result)
        cnt+= 1

        key = cv2.waitKey(1)
        if key & 0xFF == 27:break

    cap.release()
    cv2.destroyAllWindows()
    return
Ejemplo n.º 14
0
def merge_all_folders(list_of_folders,
                      folder_out,
                      target_W,
                      target_H,
                      filename_watermark=None):

    if filename_watermark is not None:
        image_watermark = cv2.imread(filename_watermark)
        w = int(target_W / 5)
        h = int(w * image_watermark.shape[0] / image_watermark.shape[1])
        image_watermark = cv2.resize(image_watermark, (w, h))
    else:
        image_watermark = None

    tools_IO.remove_files(folder_out, create=True)

    pad = 0
    bg_color = (255, 255, 255)
    empty = numpy.full((target_H, target_W, 3),
                       numpy.array(bg_color, dtype=numpy.uint8),
                       dtype=numpy.uint8)

    cnt = 0
    for folder_in in list_of_folders:

        for filename_in in tools_IO.get_filenames(folder_in, '*.jpg,*.png'):
            base_name, ext = filename_in.split('/')[-1].split(
                '.')[0], filename_in.split('/')[-1].split('.')[1]
            image = cv2.imread(folder_in + filename_in)
            image = tools_image.smart_resize(image,
                                             target_H - 2 * pad,
                                             target_W - 2 * pad,
                                             bg_color=bg_color)
            result = tools_image.put_image(empty, image, pad, pad)
            if filename_watermark is not None:
                result = tools_image.put_image(
                    result, image_watermark, 0,
                    result.shape[1] - image_watermark.shape[1])

            cv2.imwrite(folder_out + 'res_%06d_' % cnt + base_name + '.png',
                        result)
            cnt += 1
            print(base_name)

    return


# ---------------------------------------------------------------------------------------------------------------------
Ejemplo n.º 15
0
    def generate_features(self,
                          path_input,
                          path_output,
                          limit=1000000,
                          mask='*.png,*.jpg'):

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

        patterns = numpy.sort(
            numpy.array([
                f.path[len(path_input):] for f in os.scandir(path_input)
                if f.is_dir()
            ]))

        for each in patterns:
            print(each)
            local_filenames = tools_IO.get_filenames(path_input + each,
                                                     mask)[:limit]
            feature_filename = path_output + '/' + each + '_' + self.name + '.txt'
            features, filenames = [], []

            if not os.path.isfile(feature_filename):
                bar = progressbar.ProgressBar(max_value=len(local_filenames))
                for b, local_filename in enumerate(local_filenames):
                    bar.update(b)
                    image = cv2.imread(path_input + each + '/' +
                                       local_filename)
                    if image is None: continue

                    pre_whitened = preprocess(cv2.resize(image, (160, 160)))
                    feature = self.__inference([pre_whitened], self.sess)

                    features.append(feature[0])
                    filenames.append(local_filename)

                features = numpy.array(features)

                mat = numpy.zeros((features.shape[0],
                                   features.shape[1] + 1)).astype(numpy.str)
                mat[:, 0] = filenames
                mat[:, 1:] = features
                tools_IO.save_mat(mat, feature_filename, fmt='%s', delim='\t')

        return


# ---------------------------------------------------------------------------------------------------------------------
Ejemplo n.º 16
0
def stage_playground(folder_out,W,H,mat_projection,mat_view,mat_model,mat_trns):

    M = pyrr.matrix44.multiply(mat_view.T, pyrr.matrix44.multiply(mat_model.T, mat_trns.T))
    rvec, tvec = tools_pr_geom.decompose_to_rvec_tvec(M)
    aperture = 0.5 * (1 - mat_projection[2][0])
    camera_matrix = tools_pr_geom.compose_projection_mat_3x3(W, H, aperture, aperture)
    H = tools_pr_geom.RT_to_H(rvec, tvec, camera_matrix)

    empty = numpy.full((R.H, R.W, 3), 32, dtype=numpy.uint8)
    result = tools_render_CV.draw_points_numpy_MVP(R.object.coord_vert, empty, R.mat_projection,R.mat_view, R.mat_model, R.mat_trns)

    ids = [(f.split('.')[0]).split('_')[1] for f in tools_IO.get_filenames(folder_out, 'screenshot*.png')]
    i = 0
    if len(ids) > 0: i = 1 + numpy.array(ids, dtype=int).max()
    cv2.imwrite(folder_out + 'screenshot_%03d.png' % i, result)
    return
Ejemplo n.º 17
0
    def process_folder(self,
                       path_input,
                       path_out,
                       list_of_masks='*.png,*.jpg',
                       limit=1000000):
        tools_IO.remove_files(path_out, create=True)
        start_time = time.time()
        local_filenames = tools_IO.get_filenames(path_input,
                                                 list_of_masks)[:limit]
        local_filenames = numpy.sort(local_filenames)
        for local_filename in local_filenames:
            self.process_file(path_input + local_filename,
                              path_out + local_filename)

        total_time = (time.time() - start_time)
        print('Processing: %s sec in total - %f per image' %
              (total_time, int(total_time) / len(local_filenames)))
        return
    def __init__(self, folder_in):

        self.scale = 1.0
        self.draw_labels = False
        self.folder_in = folder_in
        self.textcolor = (0, 0, 0)
        self.memorized = []

        self.display_primitives = 'L'
        self.w = 2
        self.image_small = None

        self.temp_line = numpy.zeros(4, dtype=numpy.int)

        self.filenames = tools_IO.get_filenames(self.folder_in, '*.jpg,*.png')
        self.filenames = numpy.unique(self.filenames)
        self.dict_filenames = {x: i for i, x in enumerate(self.filenames)}

        self.current_frame_ID = 0
        self.image_to_display = None
        self.current_markup_ID = 0
        self.last_insert_size = 1

        self.Lines = None
        self.Boxes = None

        if self.display_primitives == 'L':
            self.Lines = Lines()
            self.Lines.read_from_file(self.folder_in + 'lines.txt',
                                      self.dict_filenames)
            self.class_names_lines = self.init_class_names_lines()
            self.colors_lines = tools_draw_numpy.get_colors(len(
                self.class_names_lines),
                                                            shuffle=True)

        if self.display_primitives == 'B':
            self.Boxes = Players(self.folder_in + 'boxes.txt',
                                 self.dict_filenames)
            self.class_names_boxes = self.init_class_names_boxes()
            self.colors_boxes = tools_draw_numpy.get_colors(
                len(self.class_names_boxes))

        self.refresh_image()
        return
Ejemplo n.º 19
0
def lm_process(folder_in, folder_out):
    filenames = numpy.array(tools_IO.get_filenames(folder_in, '*.jpg,*.png'))
    tools_IO.remove_files(folder_out, create=True)
    clr = (255 * numpy.array(R.bg_color[:3])).astype(numpy.int)

    D = detector_landmarks.detector_landmarks(
        '..//_weights//shape_predictor_68_face_landmarks.dat',
        filename_markers1)
    L_prev = None

    for filename_in in filenames:
        time_start = time.time()
        base_name, ext = filename_in.split('/')[-1].split(
            '.')[0], filename_in.split('/')[-1].split('.')[1]
        image = cv2.imread(folder_in + filename_in)
        gray = tools_image.desaturate(image)
        L = D.get_landmarks(image)

        #if not numpy.all(L==0):L_prev = L.copy()
        #else:L = L_prev.copy()

        rvec, tvec = D.get_pose_perspective(image, L, D.model_68_points,
                                            R.mat_trns)
        image_3d = R.get_image_perspective(rvec,
                                           tvec,
                                           lookback=True,
                                           scale=(1, 2, 1))

        #RT = tools_pr_geom.compose_RT_mat(rvec, tvec,do_rodriges=True)
        #image_3d = R.get_image_perspective_M(RT, lookback=True, scale=(1, 2, 1))

        #image_3d = cv2.flip(image_3d,1)
        #gray = cv2.imread('D:\LM\out11/'+base_name+'.jpg')
        #gray = tools_image.do_resize(gray,(image_3d.shape[1],image_3d.shape[0]))

        result = D.draw_landmarks_v2(gray, L, color=(0, 0, 200), w=4)
        #result = D.draw_annotation_box(result, rvec, tvec, color=(0, 128, 255), w=3)

        #result = tools_image.blend_avg(gray, image_3d, clr, weight=0.25)
        cv2.imwrite(folder_out + base_name + '.png', result)
        print('%s : %1.2f sec' % (base_name, (time.time() - time_start)))

    return
Ejemplo n.º 20
0
def get_proj_dist_mat_for_images(folder_in,chess_rows,chess_cols,cell_size=1,folder_out=None):

    x, y = numpy.meshgrid(range(chess_rows), range(chess_cols))
    world_points = numpy.hstack((x.reshape(chess_rows*chess_cols, 1), y.reshape(chess_rows*chess_cols, 1), numpy.zeros((chess_rows*chess_cols, 1)))).astype(numpy.float32)

    _3d_points = []
    _2d_points = []


    for local_filename in tools_IO.get_filenames(folder_in,'*.png,*.jpg'):
        image = cv2.imread(folder_in+local_filename)
        #image = tools_image.do_rescale(image, 0.5)
        gray = tools_image.desaturate(image)
        ret, corners = cv2.findChessboardCorners(cv2.cvtColor(image, cv2.COLOR_BGR2GRAY), (chess_rows, chess_cols),cv2.CALIB_CB_ADAPTIVE_THRESH)

        if ret:
            corners = cv2.cornerSubPix(cv2.cvtColor(image, cv2.COLOR_BGR2GRAY), corners, (11, 11), (-1, -1),(cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001))
            _2d_points.append(corners)
            _3d_points.append(world_points)
            corners = corners.reshape(-1, 2)
            for i in range(0,corners.shape[0]):gray = tools_draw_numpy.draw_circle(gray, corners[i, 1], corners[i, 0], 3, [0, 0, 255], alpha_transp=0)

        print(local_filename,len(corners))
        if folder_out!=None:
            cv2.imwrite(folder_out + local_filename, gray)

    #camera_matrix = numpy.array([[im.shape[1], 0, im.shape[0]], [0, im.shape[0], im.shape[1]], [0, 0, 1]]).astype(numpy.float64)
    #dist=numpy.zeros((1,5))

    flag = cv2.CALIB_USE_INTRINSIC_GUESS + cv2.CALIB_ZERO_TANGENT_DIST + cv2.CALIB_RATIONAL_MODEL

    matrix_init = numpy.zeros((3, 3), numpy.float32)
    matrix_init[0][0] = image.shape[1]
    matrix_init[1][1] = image.shape[0]
    matrix_init[0][2] = matrix_init[0][0]/2
    matrix_init[1][2] = matrix_init[1][1]/2
    matrix_init[2][2] = 1.0
    dist_init = numpy.zeros((1, 4), numpy.float32)
    ret, camera_matrix, dist, rvecs, tvecs = cv2.calibrateCamera(1.0 * numpy.array(_3d_points), _2d_points,(image.shape[1], image.shape[0]), matrix_init,dist_init, flags=flag)
    print(camera_matrix)
    ret, camera_matrix, dist, rvecs, tvecs = cv2.calibrateCamera(cell_size*numpy.array(_3d_points), _2d_points, (image.shape[1], image.shape[0]), matrix_init, dist_init,flags=flag)

    return camera_matrix,dist,rvecs, tvecs
Ejemplo n.º 21
0
def folder_to_video(folder_in,
                    filename_out,
                    mask='*.jpg',
                    framerate=24,
                    resize_W=None,
                    resize_H=None,
                    do_reverce=False,
                    silent=False):
    fileslist = tools_IO.get_filenames(folder_in, mask)
    fileslist.sort()

    if resize_W is None or resize_H is None:
        image = cv2.imread(os.path.join(folder_in, fileslist[0]))
        resize_H, resize_W = image.shape[:2]

    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    out = cv2.VideoWriter(filename_out, fourcc, framerate,
                          (resize_W, resize_H))

    if not silent:
        bar = progressbar.ProgressBar(len(fileslist))
        bar.start()
    for b, filename in enumerate(fileslist):
        if not silent:
            bar.update(b)
        image = cv2.imread(os.path.join(folder_in, filename))
        if resize_W is not None and resize_H is not None:
            image = cv2.resize(image, (resize_W, resize_H),
                               interpolation=cv2.INTER_CUBIC)
        out.write(image)

    if do_reverce:
        for filename in reversed(fileslist):
            image = cv2.imread(os.path.join(folder_in, filename))
            if resize_W is not None and resize_H is not None:
                image = cv2.resize(image, (resize_W, resize_H),
                                   interpolation=cv2.INTER_CUBIC)
            out.write(image)

    out.release()
    cv2.destroyAllWindows()
Ejemplo n.º 22
0
 def process_folder_negatives(self,
                              path_input,
                              path_out,
                              list_of_masks='*.png,*.jpg',
                              limit=1000000,
                              confidence=0.80):
     tools_IO.remove_files(path_out)
     local_filenames = tools_IO.get_filenames(path_input,
                                              list_of_masks)[:limit]
     local_filenames = numpy.sort(local_filenames)
     for local_filename in local_filenames:
         image = cv2.imread(path_input + local_filename)
         if image is None: return []
         boxes_yxyx, classes, scores = self.process_image(image)
         if len(scores) > 0 and scores[0] >= confidence:
             filename_out = path_out + '%02d_' % int(
                 100 * scores[0]) + local_filename
             tools_YOLO.draw_and_save(filename_out, image, boxes_yxyx,
                                      scores, classes, self.colors,
                                      self.class_names)
     return
Ejemplo n.º 23
0
def folder_to_animated_gif_imageio(path_input,
                                   filename_out,
                                   mask='*.png',
                                   framerate=10,
                                   resize_H=64,
                                   resize_W=64,
                                   do_reverce=False):
    tools_IO.remove_file(filename_out)

    images = []
    filenames = tools_IO.get_filenames(path_input, mask)

    bar = progressbar.ProgressBar(max_value=len(filenames))
    bar.start()
    for b, filename_in in enumerate(filenames):
        bar.update(b)
        image = cv2.imread(path_input + filename_in)
        image = tools_image.do_resize(image, (resize_W, resize_H))
        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        images.append(image)

    images = numpy.array(images, dtype=numpy.uint8)

    if not do_reverce:
        imageio.mimsave(filename_out, images, 'GIF', duration=1 / framerate)
    else:
        images_all = []
        for image in images:
            images_all.append(image)
        for image in reversed(images):
            images_all.append(image)

        images_all = numpy.array(images_all, dtype=images.dtype)

        imageio.mimsave(filename_out,
                        images_all,
                        'GIF',
                        duration=1 / framerate)

    return
Ejemplo n.º 24
0
    def process_folder_faceswap(self,filename_clbrt,folder_in, folder_out):

        tools_IO.remove_files(folder_out, create=True)
        local_filenames = tools_IO.get_filenames(folder_in, '*.jpg')
        image_clbrt = cv2.imread(filename_clbrt)
        L_clbrt = self.D.get_landmarks(image_clbrt)
        del_triangles_C = Delaunay(L_clbrt).vertices
        R_c = tools_GL.render_GL(image_clbrt)

        image_actor = cv2.imread(folder_in + local_filenames[0])
        R_a = tools_GL.render_GL(image_actor)

        for local_filename in local_filenames:

            image_actor = cv2.imread(folder_in + local_filename)
            L_actor = self.D.get_landmarks(image_actor)
            R_a.update_texture(image_actor)

            result = self.do_faceswap(R_c, R_a, image_clbrt, image_actor, L_clbrt, L_actor, del_triangles_C)
            cv2.imwrite(folder_out + local_filename, result)

            print(local_filename)
        return
Ejemplo n.º 25
0
    def process_folder(self,
                       path_input,
                       path_out,
                       list_of_masks='*.png,*.jpg',
                       limit=1000000,
                       markup_only=False):
        tools_IO.remove_files(path_out)
        start_time = time.time()
        local_filenames = tools_IO.get_filenames(path_input,
                                                 list_of_masks)[:limit]

        result = [('filename', 'x_left', 'y_top', 'x_right', 'y_bottom',
                   'class_ID', 'confidence')]
        local_filenames = numpy.sort(local_filenames)
        for local_filename in local_filenames:
            filename_out = path_out + local_filename if not markup_only else None
            for each in self.process_file(path_input + local_filename,
                                          filename_out):
                result.append(each)
            tools_IO.save_mat(result, path_out + 'markup_res.txt', delim=' ')
        total_time = (time.time() - start_time)
        print('Processing: %s sec in total - %f per image' %
              (total_time, int(total_time) / len(local_filenames)))
        return
Ejemplo n.º 26
0
        process_key(key)
        if key & 0xFF == 27: break

    if use_camera:
        cap.release()
    cv2.destroyAllWindows()

    return


# ---------------------------------------------------------------------------------------------------------------------
if __name__ == '__main__':

    folder_in = './images/ex_faceswap/01/'
    folder_out = './images/output1/'
    list_filenames = tools_IO.get_filenames(folder_in, '*.jpg')

    filename_clbrt, filename_actor = list_filenames[-1], list_filenames[1]
    #filename_clbrt = folder_in+'Person5c.jpg'
    #filename_actor = folder_in+'Person2a.jpg'
    image_clbrt = cv2.imread(folder_in + filename_clbrt)
    image_actor = cv2.imread(folder_in + filename_actor)

    FS = tools_faceswap.Face_Swaper(D,
                                    image_clbrt,
                                    image_actor,
                                    device='cpu',
                                    adjust_every_frame=True,
                                    do_narrow_face=True)
    demo_live(FS)