使用 Tensorflow Api 和 Opencv 在视频上裁剪检测到的对象

Posted

技术标签:

【中文标题】使用 Tensorflow Api 和 Opencv 在视频上裁剪检测到的对象【英文标题】:Cropping A Detected Object On A Video With Tensorflow Api And Opencv 【发布时间】:2018-12-29 15:31:21 【问题描述】:

-Python 3.6 -Tensorflow 1.11 支持 GPU。 -Opencv 3.4.2

我正在研究 Tensorflow Api,并且我已经训练了我的数据集。它工作正常。但是我必须裁剪检测到的对象并对其进行一些预处理。这看起来很简单,因为 Tensroflow 也用绿色框绘制了检测到的对象。当我尝试找到对象的坐标时,它给了我 0 到 1 范围内的数字。当我将坐标放在 Opencv Crop Image 上时,我必须将图像与图片的高度和宽度相乘,但它会出错。

Tensorflow.org 说我可以使用“tf.image.crop_and_resize”函数。但我不能在我自己的代码上运行它。

这是我的 run_inference_for_single_image 函数并返回 output_dict:

def run_inference_for_single_image(image, graph):
with graph.as_default():
#with tf.Session() as sess:
  # Get handles to input and output tensors
  ops = tf.get_default_graph().get_operations()
  all_tensor_names = output.name for op in ops for output in op.outputs
  tensor_dict = 
  for key in [
      'num_detections', 'detection_boxes', 'detection_scores',
      'detection_classes', 'detection_masks'
  ]:
    tensor_name = key + ':0'
    if tensor_name in all_tensor_names:
      tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(
          tensor_name)
  if 'detection_masks' in tensor_dict:
    # The following processing is only for single image
    detection_boxes = tf.squeeze(tensor_dict['detection_boxes'], [0])
    detection_masks = tf.squeeze(tensor_dict['detection_masks'], [0])
    # Reframe is required to translate mask from box coordinates to image coordinates and fit the image size.
    real_num_detection = tf.cast(tensor_dict['num_detections'][0], tf.int32)
    detection_boxes = tf.slice(detection_boxes, [0, 0], [real_num_detection, -1])
    detection_masks = tf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1])
    detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(
        detection_masks, detection_boxes, image.shape[0], image.shape[1])
    detection_masks_reframed = tf.cast(
        tf.greater(detection_masks_reframed, 0.5), tf.uint8)
    # Follow the convention by adding back the batch dimension
    tensor_dict['detection_masks'] = tf.expand_dims(
        detection_masks_reframed, 0)
  image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')

  # Run inference
  output_dict = sess.run(tensor_dict,
                         feed_dict=image_tensor: np.expand_dims(image, 0))

  # all outputs are float32 numpy arrays, so convert types as appropriate
  output_dict['num_detections'] = int(output_dict['num_detections'][0])
  output_dict['detection_classes'] = output_dict[
      'detection_classes'][0].astype(np.uint8)
  output_dict['detection_boxes'] = output_dict['detection_boxes'][0]
  output_dict['detection_scores'] = output_dict['detection_scores'][0]
  if 'detection_masks' in output_dict:
    output_dict['detection_masks'] = output_dict['detection_masks'][0]
return output_dict

这是我的视频捕捉功能。它裁剪了错误的坐标。

video = cv2.VideoCapture(0)
ret = video.set(3,1080)
ret = video.set(4,720)

while(True):

    # Acquire frame and expand frame dimensions to have shape: [1, None, None, 3]
    # i.e. a single-column array, where each item in the column has the pixel RGB value
    ret,frame = video.read()
    frame = cv2.flip(frame, 1)

    frame_expanded = np.expand_dims(frame, axis=0)

    # Perform the actual detection by running the model with the image as input
    (boxes, scores, classes, num) = sess.run(
        [detection_boxes, detection_scores, detection_classes, num_detections],
        feed_dict=image_tensor: frame_expanded)


    vis_util.visualize_boxes_and_labels_on_image_array(
        frame,
        np.squeeze(boxes),
        np.squeeze(classes).astype(np.int32),
        np.squeeze(scores),
        category_index,
        use_normalized_coordinates=True,
        line_thickness=8,
        min_score_thresh=0.50)
    # Draw the results of the detection (aka 'visulaize the results')
    output_dict = run_inference_for_single_image(frame, detection_graph)
    max_boxes_to_draw = output_dict['detection_boxes'].shape[0]
    for i in range(min(max_boxes_to_draw, output_dict['detection_boxes'].shape[0])):
        if output_dict['detection_scores'][i] > 0.95:
            if output_dict['detection_classes'][i] in category_index.keys():
                class_name = category_index[output_dict['detection_classes'][i]]['name']
                print(output_dict['detection_boxes'][i])



                crop_img = frame[int((output_dict['detection_boxes'][i][0]) * 720): int(
                    (output_dict['detection_boxes'][i][2]) * 720),
                           int((output_dict['detection_boxes'][i][1]) * 1080):int(
                               (output_dict['detection_boxes'][i][3]) * 1080)]

                cv2.imshow("asdasd", crop_img)
                print(class_name)

    cv2.imshow('Object detector', frame)
    # Press 'q' to quit
    if cv2.waitKey(1) == ord('q'):
        break

可能是关于 output_dict。

class_name = category_index[output_dict['detection_classes'][i]]['name'] => 这些代码给了我类的名称。效果很好。

【问题讨论】:

SO 允许将图像复制粘贴到您的问题中。查看一些输出可能会有所帮助。另外,你能验证 output_dict['detection_boxes'][i] 的格式是 [y0,x0,y1,x1] 吗?请注意,在 numpy 形式中,图像是 y-x,而不是 x-y。如果你把它弄混了,它可能解释一下。但什么也没看到,很难说。 【参考方案1】:

我找到了我的问题的答案。这是解决方案代码:

while(True):

# Acquire frame and expand frame dimensions to have shape: [1, None, None, 3]
# i.e. a single-column array, where each item in the column has the pixel RGB value
ret,frame = video.read()
frame = cv2.flip(frame, 1)

frame_expanded = np.expand_dims(frame, axis=0)

# Perform the actual detection by running the model with the image as input
(boxes, scores, classes, num) = sess.run(
    [detection_boxes, detection_scores, detection_classes, num_detections],
    feed_dict=image_tensor: frame_expanded)


vis_util.visualize_boxes_and_labels_on_image_array(
    frame,
    np.squeeze(boxes),
    np.squeeze(classes).astype(np.int32),
    np.squeeze(scores),
    category_index,
    use_normalized_coordinates=True,
    line_thickness=8,
    min_score_thresh=0.50)
# Draw the results of the detection (aka 'visulaize the results')
output_dict = run_inference_for_single_image(frame, detection_graph)
max_boxes_to_draw = output_dict['detection_boxes'].shape[0]
for i in range(min(max_boxes_to_draw, output_dict['detection_boxes'].shape[0])):
    if output_dict['detection_scores'][i] > 0.80:
        if output_dict['detection_classes'][i] in category_index.keys():
            class_name = category_index[output_dict['detection_classes'][i]]['name']
            #print(output_dict['detection_boxes'][i])
            ymin = boxes[0, i, 0]
            xmin = boxes[0, i, 1]
            ymax = boxes[0, i, 2]
            xmax = boxes[0, i, 3]
            im_width = 1280
            im_height = 720
            (xminn, xmaxx, yminn, ymaxx) = (xmin * im_width, xmax * im_width, ymin * im_height, ymax * im_height)
            crop_img=tf.image.crop_to_bounding_box(frame,int(yminn), int(xminn), int(ymaxx-yminn), int(xmaxx-xminn))
            crop_img=frame[int(yminn):int(ymaxx),int(xminn):int(xmaxx)]

            # print(session.run(file))

            """crop_img = frame[int((output_dict['detection_boxes'][i][0]) * 720): int(
                (output_dict['detection_boxes'][i][2]) * 720),
                       int((output_dict['detection_boxes'][i][1]) * 1080):int(
                           (output_dict['detection_boxes'][i][3]) * 1080)]"""
            cv2.imshow("asdsda",crop_img)
            #print(class_name)

cv2.imshow('Object detector', frame)
# Press 'q' to quit
if cv2.waitKey(1) == ord('q'):
     break

im_width = 1280 对我来说没有任何意义,但它适用于我的项目,但它有效。感谢您的帮助。

【讨论】:

以上是关于使用 Tensorflow Api 和 Opencv 在视频上裁剪检测到的对象的主要内容,如果未能解决你的问题,请参考以下文章

干货使用TensorFlow官方Java API调用TensorFlow模型(附代码)

在 TensorFlow 对象检测 API 中打印类名和分数

Tensorflow 2.0—— 跟着官方demo学习Tensorflow 2.0框架基本API和用法

使用 TensorFlow 的数据集 API 的图像摘要

如何将 Tensorflow 数据集 API 与训练和验证集一起使用

Tensorflow 缺少静态库中的 c_api