def save_image(self):
        """Save a timestamped image with bounding boxes around plates."""
        draw = ImageDraw.Draw(self._image)

        decimal_places = 3
        for vehicle in self._results:
            box = (
                round(vehicle['box']["ymin"] / self._image_height,
                      decimal_places),
                round(vehicle['box']["xmin"] / self._image_width,
                      decimal_places),
                round(vehicle['box']["ymax"] / self._image_height,
                      decimal_places),
                round(vehicle['box']["xmax"] / self._image_width,
                      decimal_places),
            )
            text = vehicle['plate']
            draw_box(
                draw,
                box,
                self._image_width,
                self._image_height,
                text=text,
                color=RED,
            )

        latest_save_path = self._save_file_folder / f"{self._name}_latest.png"
        self._image.save(latest_save_path)

        if self._save_timestamped_file:
            timestamp_save_path = self._save_file_folder / f"{self._name}_{self._last_detection}.png"
            self._image.save(timestamp_save_path)
            _LOGGER.info("platerecognizer saved file %s", timestamp_save_path)
    def save_image(self, pil_image: Image, directory: Path):
        """Draws the actual bounding box of the detected objects."""
        image_width, image_height = pil_image.size
        draw = ImageDraw.Draw(pil_image)
        for face in self.faces:
            if not self._show_boxes:
                break
            name = face["name"]
            confidence = face["confidence"]
            box = face["bounding_box"]
            box_label = f"{name}: {confidence:.1f}%"

            draw_box(
                draw,
                (box["y_min"], box["x_min"], box["y_max"], box["x_max"]),
                image_width,
                image_height,
                text=box_label,
                color=RED,
            )

        latest_save_path = (
            directory / f"{get_valid_filename(self._name).lower()}_latest.jpg")
        pil_image.save(latest_save_path)

        if self._save_timestamped_file:
            timestamp_save_path = directory / f"{self._name}_{self._last_detection}.jpg"
            pil_image.save(timestamp_save_path)
            _LOGGER.info("Deepstack saved file %s", timestamp_save_path)
示例#3
0
    def save_image(self, targets, directory) -> str:
        """Draws the actual bounding box of the detected objects.

        Returns: saved_image_path, which is the path to the saved timestamped file if configured, else the default saved image.
        """
        try:
            img = self._image.convert("RGB")
        except UnidentifiedImageError:
            _LOGGER.warning("Rekognition unable to process image, bad data")
            return
        draw = ImageDraw.Draw(img)

        roi_tuple = tuple(self._roi_dict.values())
        if roi_tuple != DEFAULT_ROI and self._show_boxes:
            draw_box(
                draw,
                roi_tuple,
                img.width,
                img.height,
                text="ROI",
                color=GREEN,
            )

        for obj in targets:
            if not self._show_boxes:
                break
            name = obj["name"]
            confidence = obj["confidence"]
            box = obj["bounding_box"]
            centroid = obj["centroid"]
            box_label = f"{name}: {confidence:.1f}%"

            draw_box(
                draw,
                (box["y_min"], box["x_min"], box["y_max"], box["x_max"]),
                img.width,
                img.height,
                text=box_label,
                color=RED,
            )

            # draw bullseye
            draw.text(
                (centroid["x"] * img.width, centroid["y"] * img.height),
                text="X",
                fill=RED,
            )

        latest_save_path = (
            directory / f"{get_valid_filename(self._name).lower()}_latest.jpg")
        img.save(latest_save_path)
        _LOGGER.info("Rekognition saved file %s", latest_save_path)
        saved_image_path = latest_save_path

        if self._save_timestamped_file:
            timestamp_save_path = directory / f"{self._name}_{self._last_detection}.jpg"
            img.save(timestamp_save_path)
            _LOGGER.info("Rekognition saved file %s", timestamp_save_path)
            saved_image_path = timestamp_save_path
        return str(saved_image_path)
    def save_image(self, image, targets, confidence, directory):
        """Draws the actual bounding box of the detected objects."""
        try:
            img = Image.open(io.BytesIO(bytearray(image))).convert("RGB")
        except UnidentifiedImageError:
            _LOGGER.warning("Deepstack unable to process image, bad data")
            return
        draw = ImageDraw.Draw(img)

        roi_tuple = tuple(self._roi_dict.values())
        if roi_tuple != DEFAULT_ROI:
            draw_box(
                draw,
                roi_tuple,
                img.width,
                img.height,
                text="ROI",
                color=GREEN,
            )

        for obj in self._objects:
            if not obj["name"] in self._targets:
                continue
            name = obj["name"]
            confidence = obj["confidence"]
            box = obj["bounding_box"]
            centroid = obj["centroid"]
            box_label = f"{name}: {confidence:.1f}%"

            if object_in_roi(self._roi_dict, centroid):
                box_colour = RED
            else:
                box_colour = YELLOW

            draw_box(
                draw,
                (box["y_min"], box["x_min"], box["y_max"], box["x_max"]),
                img.width,
                img.height,
                text=box_label,
                color=box_colour,
            )

            # draw bullseye
            draw.text(
                (centroid["x"] * img.width, centroid["y"] * img.height),
                text="X",
                fill=box_colour,
            )

        latest_save_path = (
            directory / f"{get_valid_filename(self._name).lower()}_latest.jpg")
        img.save(latest_save_path)

        if self._save_timestamped_file:
            timestamp_save_path = directory / f"{self._name}_{self._last_detection}.jpg"
            img.save(timestamp_save_path)
            _LOGGER.info("Deepstack saved file %s", timestamp_save_path)
示例#5
0
    def save_image(self, image, people, faces, directory):
        """Save a timestamped image with bounding boxes around targets."""

        img = Image.open(io.BytesIO(bytearray(image))).convert("RGB")
        draw = ImageDraw.Draw(img)

        for person in people:
            box = hound.bbox_to_tf_style(person["boundingBox"],
                                         self._image_width, self._image_height)
            draw_box(draw,
                     box,
                     self._image_width,
                     self._image_height,
                     color=RED)

        for face in faces:
            age = str(face["age"])
            gender = face["gender"]
            face_description = f"{gender}_{age}"
            bbox = hound.bbox_to_tf_style(face["boundingBox"],
                                          self._image_width,
                                          self._image_height)
            draw_box(
                draw,
                bbox,
                self._image_width,
                self._image_height,
                text=face_description,
                color=RED,
            )

        latest_save_path = directory + "{}_latest.jpg".format(self._name)
        out_file = open(latest_save_path, "wb")
        img.save(out_file, format="JPEG")
        out_file.flush()
        os.fsync(out_file)
        out_file.close()
        self.fire_saved_file_event(latest_save_path)

        if self._save_timestamped_file:
            timestamp_save_path = directory + "{} {}.jpg".format(
                self._name, self._last_detection)

            out_file = open(timestamp_save_path, "wb")
            img.save(out_file, format="JPEG")
            out_file.flush()
            os.fsync(out_file)
            out_file.close()
            self.fire_saved_file_event(timestamp_save_path)
            _LOGGER.info("Saved %s", timestamp_save_path)
示例#6
0
    def save_image(self, image, objects, target, directory):
        """Save a timestamped image with bounding boxes around targets."""

        img = Image.open(io.BytesIO(bytearray(image))).convert("RGB")
        draw = ImageDraw.Draw(img)

        for obj in objects:
            obj_confidence = gv.format_confidence(obj.score)
            if obj_confidence > self._confidence:
                if obj.name.lower(
                ) == target and obj_confidence >= self._confidence:
                    box = gv.get_box(obj.bounding_poly.normalized_vertices)
                    draw_box(draw, box, img.width, img.height)

        latest_save_path = directory + "google_vision_latest_{}.jpg".format(
            target)
        img.save(latest_save_path)
    def save_image(self, image, predictions, target, directory):
        """Save a timestamped image with bounding boxes around targets."""
        img = Image.open(io.BytesIO(bytearray(image))).convert("RGB")
        draw = ImageDraw.Draw(img)

        for prediction in predictions:
            prediction_confidence = ds.format_confidence(prediction["score"])
            if (prediction["name"] in target
                    and prediction_confidence >= self._confidence):
                draw_box(
                    draw,
                    prediction['box'],
                    self._image_width,
                    self._image_height,
                    text=str(prediction_confidence),
                    color=RED,
                )

        latest_save_path = directory + "{}_latest_{}.jpg".format(
            self._name, target[0])
        img.save(latest_save_path)
    def save_image(self, image, people, directory):
        """Save a timestamped image with bounding boxes around targets."""
        try:
            img = Image.open(io.BytesIO(bytearray(image))).convert("RGB")
        except UnidentifiedImageError:
            _LOGGER.warning("Sighthound unable to process image, bad data")
            return
        draw = ImageDraw.Draw(img)

        for person in people:
            box = hound.bbox_to_tf_style(person["boundingBox"],
                                         self._image_width, self._image_height)
            draw_box(draw, box, self._image_width, self._image_height)

        latest_save_path = directory / f"{self._name}_latest.jpg"
        img.save(latest_save_path)

        if self._save_timestamped_file:
            timestamp_save_path = directory / f"{self._name}_{self._last_detection}.jpg"
            img.save(timestamp_save_path)
            _LOGGER.info("Sighthound saved file %s", timestamp_save_path)
    def save_image(self):
        draw = ImageDraw.Draw(self._image)
        roi_tuple = (self._y_min, self._x_min, self._y_max, self._x_max)
        draw_box(
            draw,
            roi_tuple,
            self._image_width,
            self._image_height,
            color=RED,
        )

        latest_save_path = (
            self._save_file_folder /
            f"{get_valid_filename(self._name).lower()}_latest.png")
        self._image.save(latest_save_path)
        _LOGGER.info("Rekognition_text saved file %s", latest_save_path)
        if self._save_timestamped_file:
            now_str = dt_util.now().strftime(DATETIME_FORMAT)
            timestamp_save_path = self._save_file_folder / f"{self._name}_{now_str}.png"
            self._image.save(timestamp_save_path)
            _LOGGER.info("Rekognition_text saved file %s", timestamp_save_path)
    def save_image(self, image, response, target, confidence, directory,
                   camera_entity):
        """Draws the actual bounding box of the detected objects."""
        try:
            img = Image.open(io.BytesIO(bytearray(image))).convert("RGB")
        except UnidentifiedImageError:
            _LOGGER.warning("Sighthound unable to process image, bad data")
            return
        draw = ImageDraw.Draw(img)

        for label in response["Labels"]:
            if (label["Confidence"] < confidence) or (label["Name"] != target):
                continue

            for instance in label["Instances"]:
                box = instance["BoundingBox"]

                x, y, w, h = box["Left"], box["Top"], box["Width"], box[
                    "Height"]
                x_max, y_max = x + w, y + h

                box_label = f'{label["Name"]}: {label["Confidence"]:.1f}%'
                draw_box(
                    draw,
                    (y, x, y_max, x_max),
                    img.width,
                    img.height,
                    text=box_label,
                )

        latest_save_path = (
            directory / f"{get_valid_filename(self._name).lower()}_latest.jpg")
        img.save(latest_save_path)

        if self._save_timestamped_file:
            timestamp_save_path = directory / f"{self._name}_{self._last_detection}.jpg"
            img.save(timestamp_save_path)
            _LOGGER.info("Deepstack saved file %s", timestamp_save_path)
    def save_image(self, image, predictions, target, directory):
        """Save a timestamped image with bounding boxes around targets."""

        img = Image.open(io.BytesIO(bytearray(image))).convert("RGB")
        draw = ImageDraw.Draw(img)

        for prediction in predictions:
            prediction_confidence = ds.format_confidence(
                prediction["confidence"])
            if (prediction["label"] == target
                    and prediction_confidence >= self._confidence):
                box = get_box(prediction, self._image_width,
                              self._image_height)
                draw_box(
                    draw,
                    box,
                    self._image_width,
                    self._image_height,
                    text=str(prediction_confidence),
                    color=RED,
                )

        latest_save_path = directory + "{}_latest_{}.jpg".format(
            self._name, target)
        img.save(latest_save_path)

        if self._save_timestamped_file:
            timestamp_save_path = directory + "{}_{}_{}.jpg".format(
                self._name, target, self._last_detection)

            out_file = open(timestamp_save_path, "wb")
            img.save(out_file, format="JPEG")
            out_file.flush()
            os.fsync(out_file)
            out_file.close()
            self.fire_saved_file_event(timestamp_save_path)
            _LOGGER.info("Saved bounding box image to %s", timestamp_save_path)
def save_image(image, response, target, confidence, directory, camera_entity):
    """Draws the actual bounding box of the detected objects."""
    img = Image.open(io.BytesIO(bytearray(image))).convert("RGB")
    draw = ImageDraw.Draw(img)

    boxes = []
    for label in response["Labels"]:
        if (label["Confidence"] < confidence) or (label["Name"] != target):
            continue

        for instance in label["Instances"]:
            box = instance["BoundingBox"]

            x, y, w, h = box["Left"], box["Top"], box["Width"], box["Height"]
            x_max, y_max = x + w, y + h

            box_label = f'{label["Name"]}: {label["Confidence"]:.1f}%'
            draw_box(
                draw, (y, x, y_max, x_max), img.width, img.height, color=(0, 212, 0)
            )

            # Use draw for the text so you can give it a color that is actually readable
            left, top, line_width, font_height = (
                img.width * box["Left"],
                img.height * box["Top"],
                3,
                12,
            )
            draw.text(
                (left + line_width, abs(top - line_width - font_height)), box_label
            )

    latest_save_path = os.path.join(
        directory, get_valid_filename(camera_entity).lower() + "_latest.jpg"
    )
    img.save(latest_save_path)
示例#13
0
    def _save_image(self, image, matches, paths):
        img = Image.open(io.BytesIO(bytearray(image))).convert("RGB")
        img_width, img_height = img.size
        draw = ImageDraw.Draw(img)

        # Draw custom global region/area
        if self._area != [0, 0, 1, 1]:
            draw_box(draw, self._area, img_width, img_height, "Detection Area",
                     (0, 255, 255))

        for label, values in matches.items():

            # Draw custom label regions/areas
            if label in self._label_areas and self._label_areas[label] != [
                    0, 0, 1, 1
            ]:
                box_label = f"{label.capitalize()} Detection Area"
                draw_box(
                    draw,
                    self._label_areas[label],
                    img_width,
                    img_height,
                    box_label,
                    (0, 255, 0),
                )

            # Draw detected objects
            for instance in values:
                box_label = f'{label} {instance["score"]:.1f}%'
                # Already scaled, use 1 for width and height
                draw_box(
                    draw,
                    instance["box"],
                    img_width,
                    img_height,
                    box_label,
                    (255, 255, 0),
                )

        for path in paths:
            _LOGGER.info("Saving results image to %s", path)
            if not os.path.exists(os.path.dirname(path)):
                os.makedirs(os.path.dirname(path), exist_ok=True)
            img.save(path)
    def _save_image(self, image, matches, paths):
        img = Image.open(io.BytesIO(bytearray(image))).convert("RGB")
        img_width, img_height = img.size
        draw = ImageDraw.Draw(img)

        # Draw custom global region/area
        if self._area != [0, 0, 1, 1]:
            draw_box(
                draw, self._area, img_width, img_height, "Detection Area", (0, 255, 255)
            )

        for category, values in matches.items():
            # Draw custom category regions/areas
            if category in self._category_areas and self._category_areas[category] != [
                0,
                0,
                1,
                1,
            ]:
                label = f"{category.capitalize()} Detection Area"
                draw_box(
                    draw,
                    self._category_areas[category],
                    img_width,
                    img_height,
                    label,
                    (0, 255, 0),
                )

            # Draw detected objects
            for instance in values:
                label = "{} {:.1f}%".format(category, instance["score"])
                draw_box(
                    draw, instance["box"], img_width, img_height, label, (255, 255, 0)
                )

        for path in paths:
            _LOGGER.info("Saving results image to %s", path)
            if not os.path.exists(os.path.dirname(path)):
                os.makedirs(os.path.dirname(path), exist_ok=True)
            img.save(path)