Esempio n. 1
0
def renderloop_imgrange(
    imgrange: Tuple[int, int],
    imgpath: str,
    wait: bool,
    view_mode: str,
    con: db.Connection,
    cursor: db.Cursor,
):

    rng = range(*imgrange)

    utils.print_boxed(
        "Output information:",
        f"Imgs to render: {len(rng)}",
        f"Rendering range: {rng}",
        f"Saves images at: {os.path.join(cng.LABELCHECK_DATA_DIR, cng.LABELCHECK_IMAGE_DIR)}",
        f"Sqlite3 DB at: {os.path.join(cng.LABELCHECK_DATA_DIR, cng.LABELCHECK_DB_FILE)}",
    )

    if wait:
        input("Press enter to start rendering\n")

    utils.print_boxed("Rendering initalized")

    commit_flag: bool = False  # To make Pylance happy
    for i, nr in enumerate(rng):
        imgfilepath = imgpath + str(nr)
        print(f"Starting to reacreate imgnr {nr}")
        utils.render_and_save(imgfilepath)
        print(f"Returned from rendering imgnr {nr}")

        try:
            mainfile.assert_image_saved(imgfilepath, view_mode)
        except FileNotFoundError as e:
            print(e)
            print("Breaking render loop")
            commit_flag == False  # Will enable commit after the loop
            break

        # Only commit in intervals
        commit_flag = not i % cng.COMMIT_INTERVAL

        if commit_flag:
            con.commit()

        sql_query = f"INSERT OR REPLACE INTO {cng.LABELCHECK_DB_TABLE} VALUES ({nr})"
        cursor.execute(sql_query)

    # If loop exited without commiting remaining stuff
    if commit_flag == False:
        con.commit()
Esempio n. 2
0
    def render_loop(self):
        """
        Provides a base behavior for blender render loops
        """
        self.initalize_imgnr_iter()
        self.assert_before_loop()

        if self.pre_loop_messages:
            utils.print_boxed("Output information:", *self.pre_loop_messages)

        if self.wait:
            input("Press enter to start rendering\n")

        utils.print_boxed("Rendering initialized")

        len_iter = len(self.imgnr_iter)
        interval_flag: bool = False  # To make Pylance happy
        for iternum, imgnr in enumerate(self.imgnr_iter):
            self.setup_scene(imgnr, **self.setup_scene_kwargs)
            imgfilepath = self.imgpath + str(imgnr)
            print(f"Starting to render imgnr {imgnr}")
            utils.render_and_save(imgfilepath)
            print(f"Returned from rendering imgnr {imgnr}")

            try:
                assert_image_saved(imgfilepath, self.view_mode)
            except FileNotFoundError as e:
                print(e)
                print("Breaking render loop")
                interval_flag == False  # Will enable callback after the loop
                break

            self.iter_callback(imgnr)

            # Only commit in intervals
            interval_flag = not imgnr % self.interval

            if interval_flag:
                self.interval_callback(imgnr)

            print("Progress: ", utils.yellow(f"{iternum+1} / {len_iter}"))

        # If loop exited without commiting remaining stuff
        # This if test is kinda redundant, but idk man
        if interval_flag == False:
            self.interval_callback(imgnr)

        self.end_callback()
Esempio n. 3
0
 def commit():
     utils.print_boxed(f"Commited to {cng.BBOX_DB_FILE}")
     con.commit()
Esempio n. 4
0
def main(
    n: int,
    bbox_modes: Sequence[str],
    wait: bool,
    stdbboxcam: bpy.types.Object,
    view_mode: str,
    nspawnrange: Tuple[int, int],
) -> None:
    """Main function for generating data with Blender

    Parameters
    ----------
    n : int
        Number of images to render
    bbox_modes : Sequence[str]
        Sequence of modes to save bounding boxes, given as strings. Available: xyz cps full std
    wait : bool
        Wait for user input before starting rendering process
    stdbboxcam : bpy.types.Object
        Camera object that is to be used for extracting 2D bounding boxes
    view_mode : str
        Essentially which cameras to render from,
    """
    check_or_create_datadir(cng.GENERATED_DATA_DIR, cng.BBOX_DB_FILE)

    scene = gen.Scenemaker()
    gen.create_metadata(scene)
    con = db.connect(str(dirpath / cng.GENERATED_DATA_DIR / cng.BBOX_DB_FILE))
    cursor = con.cursor()

    datavisitor = gen.DatadumpVisitor(stdbboxcam=stdbboxcam, bbox_modes=bbox_modes, cursor=cursor)

    maxids = [
        gen.get_max_imgid(cursor, table) for table in (cng.BBOX_DB_TABLE_CPS, cng.BBOX_DB_TABLE_XYZ)
    ]

    maxid = max(maxids)

    if maxid < 0:
        maxid = 0
    else:
        maxid += 1

    imgpath = str(dirpath / cng.GENERATED_DATA_DIR / cng.IMAGE_DIR / cng.IMAGE_NAME)

    utils.print_boxed(
        "Output information:",
        f"Imgs to render: {n}",
        f"Starting at index: {maxid}",
        f"Ends at index: {maxid+n-1}",
        f"Saves images at: {os.path.join(cng.GENERATED_DATA_DIR, cng.IMAGE_DIR)}",
        f"Sqlite3 DB at: {os.path.join(cng.GENERATED_DATA_DIR, cng.BBOX_DB_FILE)}",
        f"Metadata at: {os.path.join(cng.GENERATED_DATA_DIR, cng.METADATA_FILE)}",
        f"bbox_modes: {bbox_modes}",
    )

    if wait:
        input("Press enter to start rendering\n")

    def commit():
        utils.print_boxed(f"Commited to {cng.BBOX_DB_FILE}")
        con.commit()

    utils.print_boxed("Rendering initialized")

    commit_flag: bool = False  # To make Pylance happy
    for iternum, i in enumerate(range(maxid, maxid + n)):
        scene.clear()
        scene.generate_scene(np.random.randint(*nspawnrange))
        imgfilepath = imgpath + str(i)
        print(f"Starting to render imgnr {i}")
        utils.render_and_save(imgfilepath)
        print(f"Returned from rendering imgnr {i}")

        try:
            assert_image_saved(imgfilepath, view_mode)
        except FileNotFoundError as e:
            print(e)
            print("Breaking render loop")
            commit_flag == False  # Will enable commit after the loop
            break

        datavisitor.set_n(i)
        datavisitor.visit(scene)

        # Only commit in intervals
        commit_flag = not i % cng.COMMIT_INTERVAL

        if commit_flag:
            commit()

        print("Progress: ", utils.yellow(f"{iternum+1} / {n}"))

    # If loop exited without commiting remaining stuff
    if commit_flag == False:
        commit()

    con.close()
Esempio n. 5
0
 def close_con(self):
     utils.print_boxed(f"Closed connection to {cng.BBOX_DB_FILE}")
     self.con.close()
Esempio n. 6
0
 def commit(self, imgnr: Optional[int] = None):
     self.con.commit()
     utils.print_boxed(f"Commited to {cng.BBOX_DB_FILE}")
Esempio n. 7
0
    assert len(minmax) == 2
    assert isinstance(minmax[0], int)
    assert isinstance(minmax[1], int)

    print(
        f"Number of fish in a scene will be sampled from {utils.yellow(f'Uniform({minmax[0]}, {minmax[1]})')}"
    )
    return minmax


if __name__ == "__main__":
    utils.print_boxed(
        "\x1b[30;43mFISH GENERATION BABYYY\x1b[m",
        "",
        f"Blender version: {bpy.app.version_string}",
        f"Python version: {sys.version.split()[0]}",
        "",
        end="\n\n",
    )

    parser = utils.ArgumentParserForBlender()

    parser.add_argument(
        "n_imgs", help="Number of images to generate, default 1", type=int, nargs="?", default=1
    )

    parser.add_argument(
        "-e",
        "--engine",
        help="Specify Blender GPU engine",
        choices=("BLENDER_EEVEE", "CYCLES"),
Esempio n. 8
0
def main(
    data_labels_dir: str,
    wait: bool,
    view_mode: str,
    *,
    imgnrs: Optional[Iterable[int]] = None,
    predfile: Optional[str] = None,
    imgrange: Optional[Tuple[int, int]] = None,
):
    n_assert_arg = (imgnrs, predfile, imgrange).count(None)
    if n_assert_arg == 0:
        raise AssertionError(
            "Expected one of ('imgnrs', 'predfile', 'imgrange') to be specified, but got none"
        )
    elif n_assert_arg != 2:
        raise AssertionError(
            "Expected ONLY one of ('imgnrs', 'predfile', 'imgrange') to be specified,"
            f" but got {3-n_assert_arg}")

    check_generated_datadir(data_labels_dir, cng.BBOX_DB_FILE)
    check_or_create_datadir(cng.LABELCHECK_DATA_DIR, cng.LABELCHECK_DB_FILE)
    loader = recon.Sceneloader(data_labels_dir)
    imgpath = str(dirpath / cng.LABELCHECK_DATA_DIR /
                  cng.LABELCHECK_IMAGE_DIR / cng.LABELCHECK_IMAGE_NAME)
    con = db.connect(
        str(dirpath / cng.LABELCHECK_DATA_DIR / cng.LABELCHECK_DB_FILE))
    cursor = con.cursor()

    output_info = []

    labeliter: Union[Iterable[int], range]
    if imgnrs:
        # renderloop_imgnrs(imgnrs, imgpath, wait, view_mode, con, cursor)
        labeliter = imgnrs
        output_info.append(f"Rendering given imgnrs")
    elif predfile:
        renderloop_predfile(predfile)
    elif imgrange:
        assert len(imgrange) == 2
        assert isinstance(imgrange[0], int)
        assert isinstance(imgrange[1], int)
        # renderloop_imgrange(imgrange, imgpath, wait, view_mode, con, cursor)
        labeliter = range(imgrange[0], imgrange[1])
        output_info.append(f"Rendering given imgrange: {labeliter}")

    utils.print_boxed(
        "Output information:",
        f"Imgs to render: {len(labeliter)}",
        *output_info,
        f"Saves images at: {os.path.join(cng.LABELCHECK_DATA_DIR, cng.LABELCHECK_IMAGE_DIR)}",
        f"Sqlite3 DB at: {os.path.join(cng.LABELCHECK_DATA_DIR, cng.LABELCHECK_DB_FILE)}",
    )

    if wait:
        input("Press enter to start rendering\n")

    utils.print_boxed("Rendering initalized")

    commit_flag: bool = False  # To make Pylance happy
    for i, nr in enumerate(labeliter):
        print(f"Reacreating imgnr: {nr}")
        loader.clear()
        loader.reconstruct_scene_from_db(nr)
        imgfilepath = imgpath + str(nr)
        print(f"Starting to render imgnr {nr}")
        utils.render_and_save(imgfilepath)
        print(f"Returned from rendering imgnr {nr}")

        try:
            mainfile.assert_image_saved(imgfilepath, view_mode)
        except FileNotFoundError as e:
            print(e)
            print("Breaking render loop")
            commit_flag == False  # Will enable commit after the loop
            break

        # Only commit in intervals
        commit_flag = not i % cng.COMMIT_INTERVAL

        if commit_flag:
            con.commit()

        cursor.execute(
            f"INSERT OR REPLACE INTO {cng.LABELCHECK_DB_TABLE} VALUES ({nr})")
        print("Progress: ", utils.yellow(f"{i+1} / {len(labeliter)}"))

    # If loop exited without commiting remaining stuff
    if commit_flag == False:
        con.commit()
Esempio n. 9
0
 def close_con(self):
     utils.print_boxed(
         f"Closed connection to generate {cng.LABELCHECK_DB_FILE}")
     self.con.close()
Esempio n. 10
0
 def commit(self, imgnr: int = None):
     utils.print_boxed(f"Commited to {cng.LABELCHECK_DB_FILE}")
     self.con.commit()
Esempio n. 11
0
    # If loop exited without commiting remaining stuff
    if commit_flag == False:
        con.commit()


def set_attrs_directories(labels_dir: str) -> None:
    """
    labels_dir: directory of original labels
    """
    cng.LABELCHECK_DATA_DIR = labels_dir


if __name__ == "__main__":
    utils.print_boxed(
        "LABEL CHECKER :^)",
        f"Blender version: {bpy.app.version_string}",
        f"Python version: {sys.version.split()[0]}",
        end="\n\n",
    )

    parser = utils.ArgumentParserForBlender()
    parser_imgnrs = parser.add_mutually_exclusive_group(required=True)

    parser_imgnrs.add_argument(
        "--imgnrs",
        help="Image numbers (that is corresponind labels) to be renderd",
        type=int,
        nargs="*",
    )

    parser_imgnrs.add_argument("--imgrange",
                               help="Render images in range",