首页 > 解决方案 > 如何在 OpenCV 中屏蔽图像。然后将图像反转成二进制数组

问题描述

我在这个 opencv/tensorflow 旅程中走了很远!我对张量流和opencv完全陌生,并且已经走到了这一步。这是我目前陷入困境的地方。感谢帮助!

所以我有一个图像。我正在使用 Tensorflow 进行对象检测,并且正在使用 open CV 在图像上绘制框。

在此处输入图像描述

我现在要做的是基本上用一种颜色填充检测到的对象,并用另一种颜色填充它之外的所有内容。例如,像这样:

在此处输入图像描述

最后,我希望将图像映射到基于颜色的二进制数组中。因此,诸如“蓝色为 1”和“绿色为 0”之类的内容可以输入图形算法以进行进一步处理。

到目前为止,这是我的代码:

 def annotate_objects(annotator, results, labels, npcv, count):
  window_name = 'Image'
  image = npcv
  filename="image"
  filename+=str(count)
  filename+=".jpg"
  for obj in results:
    # Convert the bounding box figures from relative coordinates
    # to absolute coordinates based on the original resolution

    height, width, channels = image.shape
    print("Image height,", height, "Image width ", width)
    ymin, xmin, ymax, xmax = obj['bounding_box']
    xmin = int(xmin * width)
    xmax = int(xmax * width)
    ymin = int(ymin * height)
    ymax = int(ymax * height)

    if obj['score'] >= 0.60:
      start_point = (xmin,ymin)

      end_point = (xmax,ymax) 

      color = (255, 0, 0) 
      thickness = 5


      image = cv2.rectangle(image, start_point, end_point, color, thickness)

      font = cv2.FONT_HERSHEY_SIMPLEX
      yminT = ymin

      yminT += 50

      org = (xmin, yminT)

      fontScale = 0.5

      color = (255, 0, 0) 
      text = labels[obj['class_id']]


      thickness = 2

      image = cv2.putText(image, text , org, font,  
                   fontScale, color, thickness, cv2.LINE_AA)


    # Overlay the box, label, and score on the camera preview
    annotator.bounding_box([xmin, ymin, xmax, ymax])
    annotator.text([xmin, ymin],
                   '%s\n%.2f' % (labels[obj['class_id']], obj['score']))

    print(labels[obj['class_id']], obj['score'])
    print(xmin, ymin, xmax, ymax)
  cv2.imwrite(filename, image)

标签: python-3.xtensorflowopencv

解决方案


您可以使用以下命令在空白图像上绘制矩形thickness=-1

mask = np.zeros(image.shape[:2], dtype=image.dtype)
mask = cv2.rectangle(mask, start_point, end_point, 255, -1)

推荐阅读