从Python中的图像裁剪并仅选择检测到的区域

问题描述 投票:2回答:1

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

例如,

Sample Input Image

enter image description here

Tensorflow Output

enter image description here

What I Want

enter image description here enter image description here

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

任何帮助将非常感谢!

python-3.x opencv tensorflow python-imaging-library object-detection-api
1个回答
1
投票

是的,在教程中,可以使用变量output_dict来实现这一点。注意传递给函数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切片来获取边界框内的图像区域

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.