コード例 #1
0
def to_keras_generator_folder_structure(images_path, labels_path):
    labels = read_labels(labels_path)

    import os

    images_path = os.path.abspath(images_path)

    out_path = os.path.abspath(images_path + "_processed")
    if not os.path.exists(out_path):
        os.makedirs(out_path)

    for _, _, files in os.walk(images_path):
        for i, f in enumerate(files):

            value = str(labels[f[:f.rfind('.')]])
            if not os.path.exists(os.path.join(out_path, value)):
                os.makedirs(os.path.join(out_path, value))

            # shutil.move(os.path.join(images_path, f), os.path.join(images_path, value, f))
            img = cv2.imread(os.path.join(images_path, f))
            img = ImageUtils.auto_crop_and_resize(img, resize_dims=RESIZE_DIMS)
            # Filpping the right eye image to the left representation
            if value.endswith('right'):
                img = ImageUtils.mirror_image(img)
            cv2.imwrite(os.path.join(out_path, value, f), img)

            print('\r{:.1%}'.format((i + 1) / len(files)), end='')
コード例 #2
0
 def track(self, frame):
     """
     更新目标的新坐标,并返回新旧质心坐标
     通过差分获取轮廓,Hu矩匹配
     :param numpy.ndArray frame:
     :return (Point, Point, list|None): 新旧坐标
     """
     if self.__last_frame is None:
         self.__last_frame = frame
         return self.__position, self.__position, None
     else:
         img = cv2.absdiff(frame, self.__last_frame)
         # 灰度处理后再高斯滤波,降低计算量
         img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
         img = cv2.GaussianBlur(img, (5, 5), 2.5)
         _, img = ImageUtils.binary(img, threshold_type=cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
         _, contours, _ = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
         min_semblance = -1
         min_moments = None
         min_index = -1
         # 计算特征的相似度
         for i, feature in enumerate(self._get_feature(contours)):
             moments, hu_moments = feature
             semblance = ImageUtils.compare_hu_moments(self.__target_hu_moments, hu_moments)
             if semblance is not False and (semblance < min_semblance or min_semblance == -1):
                 min_semblance = semblance
                 min_moments = moments
                 min_index = i
         self.__last_frame = frame
         if min_moments:
             old_position = self.__position
             self.__position = ImageUtils.get_centroid(min_moments)
             return old_position, self.__position, contours[min_index]
         else:
             return self.__position, self.__position, None
コード例 #3
0
ファイル: common.py プロジェクト: wanxinjun/mask_rcnn_pro
 def __init__(self, batch_size, **kwargs):
     super(DetectionLayer, self).__init__(**kwargs)
     self.batch_size = batch_size
     self.detection_max_instances = cfg.TEST.DETECTION_MAX_INSTANCES
     self.image_utils = ImageUtils()
     self.bbox_utils = BboxUtil()
     self.misc_utils = MiscUtils()
コード例 #4
0
 def test_dilate(self):
     """
     膨胀
     """
     ret = ImageUtils.morphology(self.__image, cv2.MORPH_DILATE, 2)
     _, ret = ImageUtils.binary(ret, threshold_type=cv2.THRESH_OTSU)
     cv2.imwrite("result/dilate.jpg", ret)
コード例 #5
0
 def test_erode(self):
     """
     腐蚀
     """
     ret = ImageUtils.morphology(self.__image, cv2.MORPH_ERODE, 2)
     _, ret = ImageUtils.binary(ret, threshold_type=cv2.THRESH_OTSU)
     cv2.imwrite("result/erode.jpg", ret)
コード例 #6
0
 def test_close(self):
     """
     闭运算
     """
     ret = ImageUtils.morphology(self.__image, cv2.MORPH_CLOSE, 8)
     _, ret = ImageUtils.binary(ret, threshold_type=cv2.THRESH_OTSU)
     cv2.imwrite("result/close.jpg", ret)
コード例 #7
0
ファイル: mask_train.py プロジェクト: wanxinjun/mask_rcnn_pro
    def __init__(self):

        self.anchor_utils = AnchorUtils()
        self.bbox_utils = BboxUtil()
        self.image_utils = ImageUtils()

        # 日志保存路径
        self.log_path = self.log_file_path(cfg.TRAIN.LOGS_PATH,
                                           cfg.TRAIN.DATA_SOURCE)
        # 模型保存路径
        self.model_save_path = cfg.TRAIN.SAVE_MODEL_PATH

        # 训练数据
        self.train_data = CocoDataset(cfg.TRAIN.COCO_TRAIN_ANN_PATH,
                                      cfg.TRAIN.COCO_TRAIN_IMAGE_PATH)
        # 验证数据
        self.val_data = CocoDataset(cfg.TRAIN.COCO_VAL_ANN_PATH,
                                    cfg.TRAIN.COCO_VAL_IMAGE_PATH)

        # 加载 mask 网络模型
        self.mask_model = MaskRCNN(train_flag=True)
        # 使用 原作者 1 + 80 类别的数据
        # self.mask_model.load_weights(cfg.TEST.COCO_MODEL_PATH, by_name=True)

        # 载入在MS COCO上的预训练模型, 跳过不一样的分类数目层
        self.mask_model.load_weights(cfg.TRAIN.MODEL_PATH,
                                     by_name=True,
                                     exclude=[
                                         "mrcnn_class_logits", "mrcnn_bbox_fc",
                                         "mrcnn_bbox", "mrcnn_mask"
                                     ])

        self.epoch = 0
        pass
コード例 #8
0
 def setUp(self):
     target = cv2.imread("result/track_target.jpg")
     mask = cv2.imread("result/mask.jpg")
     self.__target = cv2.cvtColor(target, cv2.COLOR_BGR2GRAY)
     _, self.__mask = ImageUtils.binary(mask,
                                        threshold_type=cv2.THRESH_OTSU)
     self.__target_key_points, self.__target_descriptors = ImageUtils.get_key_points(
         self.__target, self.__mask)
コード例 #9
0
    def start() -> int:
        """Starts the process of completing a generic setup that supports the 'Play Again' logic.

        Returns:
            (int): Number of runs completed.
        """
        from bot.game import Game

        runs_completed = 0

        MessageLog.print_message(
            f"\n[GENERIC] Now checking for run eligibility...")

        # Bot can start either at the Combat screen with the "Attack" button visible or the Loot Collection screen with the "Play Again" button visible.
        if ImageUtils.find_button("attack", tries=5):
            MessageLog.print_message(
                f"[GENERIC] Bot is at the Combat screen. Starting Combat Mode now..."
            )
            if CombatMode.start_combat_mode():
                runs_completed = Game.collect_loot(is_completed=True)
        else:
            MessageLog.print_message(
                f"[GENERIC] Bot is not at the Combat screen. Checking for the Loot Collection screen now..."
            )

            # Press the "Play Again" button if necessary, otherwise start Combat Mode.
            if Game.find_and_click_button("play_again"):
                Game.check_for_popups()
            else:
                raise GenericException(
                    "Failed to detect the 'Play Again' button. Bot can start either at the Combat screen with the 'Attack' button visible or the Loot Collection screen with the 'Play Again' button visible.."
                )

            # Check for AP.
            Game.check_for_ap()

            # Check if the bot is at the Summon Selection screen.
            if ImageUtils.confirm_location("select_a_summon", tries=30):
                summon_check = Game.select_summon(Settings.summon_list,
                                                  Settings.summon_element_list)
                if summon_check:
                    # Do not select party and just commence the mission.
                    MessageLog.print_message(
                        f"[GENERIC] Skipping party selection and immediately commencing mission..."
                    )
                    if Game.find_and_click_button("ok", tries=10):
                        # Now start Combat Mode and detect any item drops.
                        if CombatMode.start_combat_mode():
                            runs_completed = Game.collect_loot(
                                is_completed=True)
                    else:
                        raise GenericException(
                            "Failed to skip party selection.")
            else:
                raise GenericException(
                    "Failed to arrive at the Summon Selection screen.")

        return runs_completed
コード例 #10
0
    def _navigate():
        """Navigates to the specified Proving Grounds mission.

        Returns:
            None
        """
        from bot.game import Game

        # Go to the Home screen.
        Game.go_back_home(confirm_location_check=True)

        MessageLog.print_message(
            f"\n[PROVING.GROUNDS] Now navigating to Proving Grounds...")

        # Go to the Event by clicking on the "Menu" button and then click the very first banner.
        Game.find_and_click_button("home_menu")
        banner_locations = ImageUtils.find_all("event_banner",
                                               custom_confidence=0.7)
        if len(banner_locations) == 0:
            banner_locations = ImageUtils.find_all("event_banner_blue",
                                                   custom_confidence=0.7)
            if len(banner_locations) == 0:
                raise ProvingGroundsException(
                    "Failed to find the Event banner.")
        MouseUtils.move_and_click_point(banner_locations[0][0],
                                        banner_locations[0][1], "event_banner")

        Game.wait(1)

        difficulty = ""
        if Settings.mission_name == "Extreme":
            difficulty = "Extreme"
        elif Settings.mission_name == "Extreme+":
            difficulty = "Extreme+"

        # Select the difficulty.
        if ImageUtils.confirm_location("proving_grounds"):
            if Game.find_and_click_button("proving_grounds_missions"):
                difficulty_button_locations = ImageUtils.find_all(
                    "play_round_button")

                if difficulty == "Extreme":
                    MouseUtils.move_and_click_point(
                        difficulty_button_locations[1][0],
                        difficulty_button_locations[1][1], "play_round_button")
                elif difficulty == "Extreme+":
                    MouseUtils.move_and_click_point(
                        difficulty_button_locations[2][0],
                        difficulty_button_locations[2][1], "play_round_button")

                # After the difficulty has been selected, click "Play" to land the bot at the Proving Grounds' Summon Selection screen.
                Game.find_and_click_button("play")
        else:
            raise ProvingGroundsException(
                "Failed to arrive at the main screen for Proving Grounds.")

        return None
コード例 #11
0
 def __init__(self, target):
     """
     构造函数
     :param numpy.ndArray target: 要跟踪的目标
     """
     self.__last_frame = None
     _, self.__target = ImageUtils.binary(target, threshold_type=cv2.THRESH_OTSU)
     self.__target_moments = cv2.moments(self.__target, True)
     self.__target_hu_moments = cv2.HuMoments(self.__target_moments)
     self.__position = ImageUtils.get_centroid(self.__target_moments)
コード例 #12
0
    def start(first_run: bool) -> int:
        """Starts the process to complete a run for Raid Farming Mode and returns the number of items detected.

        Args:
            first_run (bool): Flag that determines whether or not to run the navigation process again. Should be False if the Farming Mode supports the "Play Again" feature for repeated runs.

        Returns:
            (int): Number of items detected.
        """
        from bot.game import Game

        number_of_items_dropped: int = 0

        # Start the navigation process.
        if first_run:
            Raid._navigate()
        else:
            # Check for Pending Battles and then perform navigation again.
            Game.check_for_pending()
            Raid._navigate()

        # Check for EP.
        Game.check_for_ep()

        # Check if the bot is at the Summon Selection screen.
        if ImageUtils.confirm_location("select_a_summon", tries=30):
            summon_check = Game.select_summon(Settings.summon_list,
                                              Settings.summon_element_list)

            if summon_check:
                # Select the Party.
                if Game.find_party_and_start_mission(Settings.group_number,
                                                     Settings.party_number):
                    # Handle the rare case where joining the Raid after selecting the Summon and Party led the bot to the Quest Results screen with no loot to collect.
                    if ImageUtils.confirm_location("no_loot", tries=2):
                        MessageLog.print_message(
                            "\n[RAID] Seems that the Raid just ended. Moving back to the Home screen and joining another Raid..."
                        )
                    elif CombatMode.start_combat_mode():
                        number_of_items_dropped = Game.collect_loot(
                            is_completed=True)
                else:
                    MessageLog.print_message(
                        "\n[RAID] Seems that the Raid ended before the bot was able to join. Now looking for another Raid to join..."
                    )
        else:
            raise RaidException(
                "Failed to arrive at the Summon Selection screen.")

        return number_of_items_dropped
コード例 #13
0
    def start(first_run: bool) -> int:
        """Starts the process to complete a run for Quest Farming Mode and returns the number of items detected.

        Args:
            first_run (bool): Flag that determines whether or not to run the navigation process again. Should be False if the Farming Mode supports the "Play Again" feature for repeated runs.

        Returns:
            (int): Number of items detected.
        """
        from bot.game import Game

        number_of_items_dropped: int = 0

        # Start the navigation process.
        if first_run:
            Quest._navigate()
        elif Game.find_and_click_button("play_again"):
            Game.check_for_popups()
        else:
            # If the bot cannot find the "Play Again" button, check for Pending Battles and then perform navigation again.
            Game.check_for_pending()
            Quest._navigate()

        # Check for AP.
        Game.check_for_ap()

        # Check if the bot is at the Summon Selection screen.
        if ImageUtils.confirm_location("select_a_summon", tries=30):
            summon_check = Game.select_summon(Settings.summon_list,
                                              Settings.summon_element_list)
            if summon_check:
                # Select the Party.
                Game.find_party_and_start_mission(Settings.group_number,
                                                  Settings.party_number)

                # Close the "Item Picked Up" popup.
                if ImageUtils.confirm_location("items_picked_up"):
                    Game.find_and_click_button("ok")

                # Now start Combat Mode and detect any item drops.
                if CombatMode.start_combat_mode():
                    number_of_items_dropped = Game.collect_loot(
                        is_completed=True)
        else:
            raise QuestException(
                "Failed to arrive at the Summon Selection screen.")

        return number_of_items_dropped
コード例 #14
0
    def _navigate():
        """Navigates to the specified Xeno Clash mission.

        Returns:
            None
        """
        from bot.game import Game

        # Go to the Home screen.
        Game.go_back_home(confirm_location_check = True)

        MessageLog.print_message(f"\n[XENO.CLASH] Now navigating to Xeno Clash...")

        # Go to the Event by clicking on the "Menu" button and then click the very first banner.
        Game.find_and_click_button("home_menu")
        event_banner_locations = ImageUtils.find_all("event_banner", custom_confidence = 0.7)
        if len(event_banner_locations) == 0:
            event_banner_locations = ImageUtils.find_all("event_banner_blue", custom_confidence = 0.7)
        MouseUtils.move_and_click_point(event_banner_locations[0][0], event_banner_locations[0][1], "event_banner")

        Game.wait(2.0)

        if Game.find_and_click_button("xeno_special", tries = 30):
            # Check to see if the user already has a Nightmare available.
            nightmare_is_available = 0
            if ImageUtils.find_button("event_nightmare", tries = 1) is not None:
                nightmare_is_available = 1

            # Find all the "Select" buttons.
            select_button_locations = ImageUtils.find_all("select")

            if Settings.mission_name == "Xeno Clash Extreme":
                MessageLog.print_message(f"[XENO.CLASH] Now hosting Xeno Clash Extreme...")
                MouseUtils.move_and_click_point(select_button_locations[1 + nightmare_is_available][0], select_button_locations[1 + nightmare_is_available][1], "select")

                difficulty_button_locations = ImageUtils.find_all("play_round_button")
                MouseUtils.move_and_click_point(difficulty_button_locations[0][0], difficulty_button_locations[0][1], "play_round_button")
            elif Settings.mission_name == "Xeno Clash Raid":
                MessageLog.print_message(f"[XENO.CLASH] Now hosting Xeno Clash Raid...")
                MouseUtils.move_and_click_point(select_button_locations[2 + nightmare_is_available][0], select_button_locations[2 + nightmare_is_available][1], "select")

                Game.wait(2.0)

                Game.find_and_click_button("play")
        else:
            raise(XenoClashException("Failed to open the Xeno Special tab."))

        return None
コード例 #15
0
 def setUp(self):
     self.__image = cv2.imread("outputs/1_0.jpg")
     if self.__image is None:
         self.fail("读取样本失败")
     _, img = ImageUtils.binary(self.__image,
                                threshold_type=cv2.THRESH_OTSU)
     cv2.imwrite("result/origin.jpg", img)
コード例 #16
0
    def _randomize_point(x: int, y: int, image_name: str):
        """Randomize the clicking location in an attempt to avoid clicking the same location that may make the bot look suspicious.

        Args:
            x (int): X coordinate on the screen of the center of the match location.
            y (int): Y coordinate on the screen of the center of the match location.
            image_name (str): File name of the image in /images/buttons/ folder.

        Returns:
            (int, int): Tuple of the newly randomized location to click.
        """
        # Get the width and height of the template image.
        from utils.image_utils import ImageUtils
        width, height = ImageUtils.get_button_dimensions(image_name)

        dimensions_x0 = x - (width // 2)
        dimensions_x1 = x + (width // 2)

        dimensions_y0 = y - (height // 2)
        dimensions_y1 = y + (height // 2)

        while True:
            new_width = random.randint(int(width * 0.2), int(width * 0.8))
            new_height = random.randint(int(height * 0.2), int(height * 0.8))

            new_x = dimensions_x0 + new_width
            new_y = dimensions_y0 + new_height

            # If the new coordinates are within the bounds of the template image, break out of the loop and return the coordinates.
            if new_x > dimensions_x0 or new_x < dimensions_x1 or new_y > dimensions_y0 or new_y < dimensions_y1:
                break

        return new_x, new_y
コード例 #17
0
 def test_median_blur(self):
     """
     中值滤波
     """
     ret = cv2.medianBlur(self.__image, 1)
     cv2.imwrite("result/median_0.jpg", ret)
     _, ret = ImageUtils.binary(ret, threshold_type=cv2.THRESH_OTSU)
     cv2.imwrite("result/median_1.jpg", ret)
コード例 #18
0
 def test_gaussian_blur(self):
     """
     高斯滤波
     """
     ret = cv2.GaussianBlur(self.__image, (3, 3), 0.8)
     cv2.imwrite("result/gaussian_0.jpg", ret)
     _, ret = ImageUtils.binary(ret, threshold_type=cv2.THRESH_OTSU)
     cv2.imwrite("result/gaussian_1.jpg", ret)
コード例 #19
0
 def test_mean_blur(self):
     """
     均值滤波
     """
     ret = cv2.pyrMeanShiftFiltering(self.__image, 3, 3)
     cv2.imwrite("result/mean_0.jpg", ret)
     _, ret = ImageUtils.binary(ret, threshold_type=cv2.THRESH_OTSU)
     cv2.imwrite("result/mean_1.jpg", ret)
コード例 #20
0
def streaming_images(files, convert_func, func_args):
    for i, f in enumerate(files):
        img = cv2.imread(f)
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        if convert_func is not None:
            # image conversion
            img = convert_func(img, func_args)
        yield ImageUtils.compress_image(img), f[f.rfind('/') + 1:]
コード例 #21
0
    def _check_for_boss() -> bool:
        """Checks for the existence of 3-3, 6-3 or 9-3 boss if user settings enabled it.

        Returns:
            (bool): Flag on whether or not a Boss was detected.
        """
        if Settings.enable_stop_on_arcarum_boss:
            MessageLog.print_message(
                f"\n[ARCARUM] Checking if boss is available...")

            if ImageUtils.find_button("arcarum_boss",
                                      tries=1) or ImageUtils.find_button(
                                          "arcarum_boss2", tries=1):
                return True
            else:
                return False
        else:
            return False
コード例 #22
0
 async def _capture(self, websocket):
     response_frame = response_pb2.FrameResponse()
     response_frame.code = 1
     response_frame.type = response_pb2.FrameResponse.VIDEO
     ret, img = Camera.get_frame()
     if ret:
         response_frame.frame = ImageUtils.img2bytes(img)
         await websocket.send(response_frame.SerializeToString())
         self.__outline.add_frame(img)
コード例 #23
0
    def _navigate():
        """Navigates to the specified Raid.

        Returns:
            None
        """
        from bot.game import Game

        MessageLog.print_message(
            f"\n[RAID] Beginning process to navigate to the raid: {Settings.mission_name}..."
        )

        # Head to the Home screen.
        Game.go_back_home(confirm_location_check=True)

        # Then navigate to the Quest screen.
        Game.find_and_click_button("quest")

        Game.wait(1)

        # Check for the "You retreated from the raid battle" popup.
        if ImageUtils.confirm_location("you_retreated_from_the_raid_battle",
                                       tries=1):
            Game.find_and_click_button("ok")

        # Check for any Pending Battles popup.
        if Game.check_for_pending():
            Game.find_and_click_button("quest")

        # Now navigate to the Raid screen.
        Game.find_and_click_button("raid")

        if ImageUtils.confirm_location("raid"):
            # Check for any joined raids and if the max number of raids joined was reached, clear them.
            Raid._check_for_joined_raids()
            Raid._clear_joined_raids()

            # Click on the "Enter ID" button and then start the process to join a raid.
            MessageLog.print_message(
                f"\n[RAID] Now moving to the \"Enter ID\" screen.")
            if Game.find_and_click_button("enter_id"):
                Raid._join_raid()
        else:
            raise RaidException("Failed to reach the Backup Requests screen.")
コード例 #24
0
 async def execute(self, websocket):
     self.__capture_scheduler.add_job(self._capture,
                                      'interval', [websocket],
                                      id=self.__capture_job_id,
                                      max_instances=3,
                                      seconds=1 / 7)
     await asyncio.wait([
         asyncio.ensure_future(self._wait_stop(websocket)),
     ])
     # 直到收到停止命令
     background, max_difference_frame = self.__outline.get_max_difference_frame(
     )
     response_frame = response_pb2.FrameResponse()
     response_frame.code = 1
     response_frame.type = response_pb2.FrameResponse.OUTLINE
     response_frame.frame = ImageUtils.img2bytes(max_difference_frame)
     await websocket.send(response_frame.SerializeToString())
     response_frame.type = response_pb2.FrameResponse.BACKGROUND
     response_frame.frame = ImageUtils.img2bytes(background)
     await websocket.send(response_frame.SerializeToString())
コード例 #25
0
 async def execute(self, websocket):
     response = await websocket.recv()
     command = request_pb2.CommandRequest()
     command.ParseFromString(response)
     self.__target = ImageUtils.bytes2img(command.frame)
     self.__tracker = MovingTargetTrack(self.__target)
     if command.code == 2:
         self.__capture = True
         await asyncio.wait([
             asyncio.ensure_future(self._send_frame(websocket)),
             asyncio.ensure_future(self._wait_stop(websocket)),
         ])
コード例 #26
0
ファイル: app_scene.py プロジェクト: cheverebe/Arkanoid-CV
    def _adapt_to_screen(self):
        screen_resolution = ScreenUtils.get_screen_resolution()
        screen_aspect_ratio = float(screen_resolution[0]) / screen_resolution[1]
        scene_aspect_ratio = float(self.dimensions[0]) / self.dimensions[1]

        if screen_aspect_ratio < scene_aspect_ratio:
            self.resize_factor = screen_resolution[0] / float(self.dimensions[0])
        else:
            self.resize_factor = screen_resolution[1] / float(self.dimensions[1])

        self.background = ImageUtils.resize_image(self.background, self.resize_factor)
        self.dimensions = self.background.shape[:2]
コード例 #27
0
 def test_prosac(self):
     """
     改进抽样一致
     """
     Camera.reset()
     self.__last_frame = None
     print("PROSAC")
     for i in range(1, 30):
         start = time.clock()
         _, frame = Camera.get_frame()
         if self.__last_frame is None:
             self.__last_frame = frame
             continue
         img = cv2.absdiff(frame, self.__last_frame)
         self.__last_frame = frame
         img = cv2.GaussianBlur(img, (5, 5), 2.5)
         img = ImageUtils.morphology(img, cv2.MORPH_DILATE, 16)
         _, img = ImageUtils.binary(img, threshold_type=cv2.THRESH_OTSU)
         # 计算特征点
         key_points, descriptors = ImageUtils.get_key_points(frame, img)
         matches = ImageUtils.knn_match(self.__target_descriptors,
                                        descriptors)
         if len(matches) > 0:
             # 匹配到合适的特征点
             points = ImageUtils.get_matches_points(key_points, matches)
             src_key_points = ImageUtils.get_matches_points(
                 self.__target_key_points, matches, 1)
             # PROSAC去除错误点
             _, mask = cv2.findHomography(src_key_points, points, cv2.RHO)
             if mask is not None:
                 points_after = points[mask.ravel() == 1]
                 end = time.clock()
                 print("%d\t%d\t%d\t%f" %
                       (i, len(points), len(points_after), end - start))
コード例 #28
0
 def _get_difference_frame(pre_frame, next_frame):
     """
     帧进行差分并二值化,二值化使用OTSU算法
     :param numpy.ndarray pre_frame: 前一帧
     :param numpy.ndarray next_frame: 后一帧
     :rtype: numpy.ndarray
     :returns: 差分帧
     """
     img = cv2.absdiff(pre_frame, next_frame)
     img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
     _, img = ImageUtils.binary(img,
                                threshold_type=cv2.THRESH_BINARY_INV
                                | cv2.THRESH_OTSU)
     return img
コード例 #29
0
def get_image():
    if (request.args.get('time')==""):
        print(request)
        abort(400)

    image = Image.objects(time=request.args.get('time')).first()

    # print(image.picture)
    pic = ImageUtils.base64topicture(image.picture)
    file = open('/search/pic.jpg','wb')
    file.write(pic)
    file.close

    perdict = ImageUtils.turi_predict('search/pic.jpg')
    image.label = perdict
    
         #判断文件是否存在
    # if(os.path.exists("search/pic.jpg")):
    #     os.remove("search/pic.jpg")

    # return jsonify({'imageinfo': image}),200
    
    return jsonify({'imageinfo': perdict}),200
コード例 #30
0
    def test_combat_mode_old_lignoid(self):
        # Make sure the bot is at the Home screen and go to the Trial Battles screen.
        self.game_object.go_back_home(confirm_location_check=True)
        MouseUtils.scroll_screen_from_home_button(-600)
        self.game_object.find_and_click_button("gameplay_extras")

        while self.game_object.find_and_click_button("trial_battles") is False:
            MouseUtils.scroll_screen_from_home_button(-300)

        self.assertTrue(ImageUtils.confirm_location("trial_battles"))
        # Click on the "Old Lignoid" button.
        self.game_object.find_and_click_button("trial_battles_old_lignoid")

        # Select any detected "Play" button.
        self.game_object.find_and_click_button("play_round_button")

        # Now select the first Summon.
        choose_a_summon_location = ImageUtils.find_button("choose_a_summon")
        MouseUtils.move_and_click_point(choose_a_summon_location[0],
                                        choose_a_summon_location[1] + 187,
                                        "choose_a_summon")

        # Now start the Old Lignoid Trial Battle right away and then wait a few seconds.
        self.game_object.find_and_click_button("party_selection_ok")
        Game.wait(3)

        if ImageUtils.confirm_location("trial_battles_description"):
            self.game_object.find_and_click_button("close")

        self.assertFalse(
            CombatMode.start_combat_mode(script_commands=[
                "Turn 1:", "\tsummon(6)", "\tcharacter1.useSkill(1)", "end",
                "", "Turn 5:", "\texit", "end"
            ]))
        self.assertTrue(ImageUtils.confirm_location("home"))
        return None