在Tensorflow Object Detection API中裁剪图像到边界框

9

我该如何在Tensorflow中使用Python API将图像剪裁到边界框?

根据文档,

tf.image.crop_to_bounding_box(image, offset_height, offset_width, target_height, target_width)

将图像裁剪为指定的边界框。

此操作从图像中截取一个矩形部分。返回图像的左上角位于图像中的 offset_height、offset_width,右下角位于 offset_height + target_height、offset_width + target_width。

我可以获取标准化坐标下的边界框坐标,例如:

    ymin = boxes[0,i,0]
    xmin = boxes[0,i,1]
    ymax = boxes[0,i,2]
    xmax = boxes[0,i,3]

并将这些转换为绝对坐标,

    (xminn, xmaxx, yminn, ymaxx) = (xmin * im_width, xmax * im_width, ymin * im_height, ymax * im_height)

然而我不知道如何在crop_to_bounding_box函数中使用这些坐标。


2个回答

10

由于我们将 x 视为水平方向,将 y 视为垂直方向,因此以下内容将使用指定框剪裁图像。

cropped_image = tf.image.crop_to_bounding_box(image, yminn, xminn, 
                                       ymaxx - yminn, xmaxx - xminn)

@IshantMrinal:你是否知道如何用颜色填充边界框内部?比如我想在图像中对某些部分进行打码。我注意到这里:https://github.com/tensorflow/models/blob/master/research/object_detection/utils/visualization_utils.py#L169 使用了PIL绘制矩形,并初始化了fill参数,但它并没有填充任何颜色!你能帮我解决这个问题吗? - Hossein

0
以下是在TensorFlow中裁剪和保存边界框的工作代码。
 for idx in range(len(bboxes)):
    if bscores[idx] >= Threshold:
      #Region of Interest
      y_min = int(bboxes[idx][0] * im_height)
      x_min = int(bboxes[idx][1] * im_width)
      y_max = int(bboxes[idx][2] * im_height)
      x_max = int(bboxes[idx][3] * im_width)

      class_label = category_index[int(bclasses[idx])]['name']
      class_labels.append(class_label)
      bbox.append([x_min, y_min, x_max, y_max, class_label, float(bscores[idx])])

      #Crop Image - Working Code
      cropped_image = tf.image.crop_to_bounding_box(image, y_min, x_min, y_max - y_min, x_max - x_min).numpy().astype(np.int32)

      # encode_jpeg encodes a tensor of type uint8 to string
      output_image = tf.image.encode_jpeg(cropped_image)
      # decode_jpeg decodes the string tensor to a tensor of type uint8
      #output_image = tf.image.decode_jpeg(output_image)

      score = bscores[idx] * 100

      file_name = tf.constant(OUTPUT_PATH+image_name[:-4]+'_'+str(idx)+'_'+class_label+'_'+str(round(score))+'%'+'_'+os.path.splitext(image_name)[1])

      writefile = tf.io.write_file(file_name, output_image)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接