首页 > 解决方案 > 在 Python 中裁剪并仅从图像中选择检测到的区域

问题描述

我使用 TensorFlow Object Detection API 从图像中检测手。通过使用提供的示例代码(object_detection_tutorial.ipynb),我已经能够在图像上绘制边界框。有没有办法只选择检测到的区域(在边界框内)并将其作为图像获取?

例如,

样本输入图像

在此处输入图像描述

张量流输出

在此处输入图像描述

我想要的是

在此处输入图像描述 在此处输入图像描述

可以在此处找到对象检测 API 示例代码。https://github.com/tensorflow/models/blob/master/research/object_detection/object_detection_tutorial.ipynb

任何帮助将不胜感激!

标签: python-3.xopencvtensorflowpython-imaging-libraryobject-detection-api

解决方案


是的,在本教程中,该变量output_dict可用于实现这一目标。注意传递给 function 的所有变量vis_util.visualize_boxes_and_labels_on_image_array,它们包含框、分数等。

首先,您需要获取图像形状,因为框坐标是标准化形式。

img_height, img_width, img_channel = image_np.shape

然后将所有框坐标转换为绝对格式

absolute_coord = []
THRESHOLD = 0.7 # adjust your threshold here
N = len(output_dict['detection_boxes'])
for i in range(N):
    if output_dict['score'][i] < THRESHOLD:
        continue
    box = output_dict['detection_boxes']
    ymin, xmin, ymax, xmax = box
    x_up = int(xmin*img_width)
    y_up = int(ymin*img_height)
    x_down = int(xmax*img_width)
    y_down = int(ymax*img_height)
    absolute_coord.append((x_up,y_up,x_down,y_down))

然后你可以使用 numpy slices 来获取边界框内的图像区域

bounding_box_img = []
for c in absolute_coord:
    bounding_box_img.append(image_np[c[1]:c[3], c[0]:c[2],:])

然后只需将所有 numpy 数组保存bounding_box_img为图像。保存时您可能需要更改形状,因为 img 的形状为 [img_height, img_width, img_channel]。如果您使用分数数组,您甚至可以过滤掉所有低置信度分数的检测。

PS:我可能搞砸了img_heightimg_width但这些应该给你一个起点。


推荐阅读