예제 #1
0
파일: dataset_edit.py 프로젝트: korhun/misc
def save_images_with_cv(source_dir_name,
                        target_dir_name,
                        max_dim=None,
                        recursive=False):
    if not os.path.isdir(target_dir_name):
        file_helper.create_dir(target_dir_name)
    i = 0
    for fn in file_helper.enumerate_files(source_dir_name,
                                          recursive=recursive):
        try:
            i += 1
            print("{} - {}".format(i, fn), end=end_txt)
            dir_name, name, extension = file_helper.get_file_name_extension(fn)
            if string_helper.equals_case_insensitive(extension, ".txt"):
                new_fn = file_helper.path_join(target_dir_name,
                                               name + extension)
                file_helper.copy_file(fn, new_fn)
            else:
                mat = cv2.imread(fn)
                if max_dim is not None:
                    mat = image_helper.resize_if_larger(mat, max_dim)
                new_fn = file_helper.path_join(target_dir_name, name + ".jpg")
                cv2.imwrite(new_fn, mat)
        except Exception as e:
            print("error - save_images_with_cv: {}".format(fn))

    print("save_images_with_cv finished")
예제 #2
0
    def get_frames(self):
        # count = 0
        self.__stream.start()
        try:
            skip = 0
            while True:
                frame = self.__stream.read()
                if frame is None:
                    break
                if self._max_dim is not None:
                    frame = resize_if_larger(frame, self._max_dim)

                if skip > 0:
                    skip = skip - 1
                else:
                    yield frame

                k = cv2.waitKey(1) & 0xFF
                if k == ord("q"):
                    break
                elif k == ord("s"):
                    skip = 10

        except StopIteration:
            pass
        finally:
            self.stop()
예제 #3
0
파일: camera_video.py 프로젝트: korhun/misc
    def get_frames(self):
        # count = 0
        try:
            skip = 0
            while self._capture.isOpened():
                ok, frame = self._capture.read()
                if frame is None:
                    break
                if self._max_dim is not None and self._max_dim > 0:
                    frame = resize_if_larger(frame, self._max_dim)
                if self._mirror:
                    frame = cv2.flip(frame, 1)
                if skip > 0:
                    skip = skip - 1
                else:
                    yield frame

                k = cv2.waitKey(1) & 0xFF
                if k == ord("q"):
                    break
                elif k == ord("s"):
                    skip = 10

        except StopIteration:
            pass
        finally:
            cv2.destroyAllWindows()
예제 #4
0
    def get_frames1(self):
        # import required libraries
        from vidgear.gears import CamGear
        import cv2

        # Add YouTube Video URL as input source (for e.g https://youtu.be/bvetuLwJIkA)
        # and enable Stream Mode (`stream_mode = True`)
        stream = CamGear(source=self.__url, stream_mode=True,
                         logging=True).start()

        skip = 0
        # loop over
        while True:

            # read frames from stream
            frame = stream.read()

            # check for frame if Nonetype
            if frame is None:
                break

            if frame is None:
                break
            if self._max_dim is not None:
                frame = resize_if_larger(frame, self._max_dim)

            if skip > 0:
                skip = skip - 1
            else:
                yield frame

            k = cv2.waitKey(1) & 0xFF
            if k == ord("q"):
                break
            elif k == ord("s"):
                skip = 10

        # close output window
        cv2.destroyAllWindows()

        # safely close video stream
        stream.stop()
예제 #5
0
파일: dataset_edit.py 프로젝트: korhun/misc
def combine_classes(class_items,
                    out_images_dir,
                    out_labels_dir,
                    out_classes_txt_fn,
                    out_style="yolo"):
    # a typical class_item
    # {
    #     "class_name": "vehicle license plate",
    #     "dirs":
    #         [
    #             {
    #                 "images": "C:/_koray/train_datasets/yolo_oidv6_class0/vehicle_registration_plate",
    #                 "labels": "C:/_koray/train_datasets/yolo_oidv6_class0/vehicle_registration_plate"
    #             },
    #             {
    #                 "images": "C:/_koray/train_datasets/yolo_misc/vehicle_registration_plate/class0",
    #                 "labels": "C:/_koray/train_datasets/yolo_misc/vehicle_registration_plate/class0"
    #             }
    #         ],
    #     "resize_style": None, "if_larger" or "crop" - if "crop" -> make the image unique, don't combine, other combine with other classes
    #     "image_size": 640, - if None no resize, combine all
    #     "style": "yolo"
    # }

    class_names = []
    if out_style == "yolo":
        if not os.path.isdir(out_images_dir):
            file_helper.create_dir(out_images_dir)

        if not os.path.isdir(out_labels_dir):
            file_helper.create_dir(out_labels_dir)

        if os.path.isfile(out_classes_txt_fn):
            for class_name in file_helper.read_lines(out_classes_txt_fn):
                class_names.append(class_name)
    else:
        raise Exception("Bad out_style: " + out_style)

    for class_item in class_items:
        class_name = class_item["class_name"]
        resize_style = class_item["resize_style"]
        image_size = class_item["image_size"]
        if image_size is not None:
            image_size_txt = "{}_{}".format(image_size[0], image_size[1])
        else:
            image_size_txt = None
        input_style = class_item["input_style"]

        if class_name in class_names:
            class_index = class_names.index(class_name)
        else:
            class_index = len(class_names)
            class_names.append(class_name)
            file_helper.append_line(out_classes_txt_fn, class_name)

        i = 0
        for dir_item in class_item["dirs"]:
            images_dir = dir_item["images"]
            labels_dir = dir_item["labels"]

            if input_style == "yolo":
                for label_fn in file_helper.enumerate_files(
                        labels_dir, wildcard_pattern="*.txt"):
                    try:
                        _dir_name, name, _extension = file_helper.get_file_name_extension(
                            label_fn)

                        i += 1
                        print("{} - {}".format(i, label_fn), end=end_txt)

                        for line in file_helper.read_lines(label_fn):
                            line_items = line.split(" ")
                            cx_norm = float(line_items[1])
                            cy_norm = float(line_items[2])
                            w_norm = float(line_items[3])
                            h_norm = float(line_items[4])
                            line_items[0] = str(class_index)

                            out_lbl_fn = None
                            out_img_fn = None
                            mat = None
                            # for image_fn in file_helper.enumerate_files(images_dir, wildcard_pattern=name + ".*"):
                            image_fn = find_image_file(images_dir, name)
                            if image_fn is not None:
                                _dir_name, _name, extension = file_helper.get_file_name_extension(
                                    image_fn)
                                if extension != ".txt":
                                    try:
                                        mat = cv2.imread(image_fn)
                                    except Exception as e:
                                        print(
                                            'Error reading image file: {} msg:{}'
                                            .format(image_fn, str(e)))
                                    if mat is not None:
                                        if image_size is None or resize_style is None:
                                            out_img_fn = file_helper.path_join(
                                                out_images_dir, name + ".jpg")
                                            out_lbl_fn = file_helper.path_join(
                                                out_labels_dir, name + ".txt")
                                        elif resize_style == "if_larger":
                                            out_img_fn = file_helper.path_join(
                                                out_images_dir, name + "_" +
                                                image_size_txt + ".jpg")
                                            out_lbl_fn = file_helper.path_join(
                                                out_labels_dir, name + "_" +
                                                image_size_txt + ".txt")
                                            mat = image_helper.resize_if_larger(
                                                mat,
                                                max(image_size[0],
                                                    image_size[1]))
                                        elif resize_style == "crop":
                                            new_name = file_helper.get_unique_file_name(
                                            )
                                            out_img_fn = file_helper.path_join(
                                                out_images_dir, name +
                                                "_crop_" + new_name + ".jpg")
                                            out_lbl_fn = file_helper.path_join(
                                                out_labels_dir, name +
                                                "_crop_" + new_name + ".txt")
                                            mat, cx, cy, w, h = crop_rect(
                                                mat, cx_norm, cy_norm, w_norm,
                                                h_norm, image_size)
                                            line_items[1] = str(cx)
                                            line_items[2] = str(cy)
                                            line_items[3] = str(w)
                                            line_items[4] = str(h)
                                        else:
                                            raise Exception(
                                                "Bad resize_style: " +
                                                resize_style)
                            else:
                                raise Exception("Cannot find image file")

                            if out_lbl_fn is not None:
                                line = string_helper.join(line_items, " ")
                                if os.path.isfile(out_lbl_fn):
                                    file_helper.append_line(out_lbl_fn, line)
                                else:
                                    file_helper.write_lines(out_lbl_fn, [line])
                            if out_img_fn is not None and mat is not None:
                                if not os.path.isfile(out_img_fn):
                                    cv2.imwrite(out_img_fn, mat)
                    except Exception as e:
                        print('Error - file:{} msg:{}'.format(
                            label_fn, str(e)))
            else:
                raise Exception("Bad input_style: " + out_style)