【问题标题】:How to mask an image in OpenCV. Then invert the image into a binary array如何在 OpenCV 中屏蔽图像。然后将图像反转成二进制数组
【发布时间】:2021-02-17 18:31:08
【问题描述】:

我在这个 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.x tensorflow opencv


【解决方案1】:

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

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

【讨论】:

  • 好的,我注意到这个蒙版将对象变为黑色,将外部区域变为白色。没关系,我可以使用它。我将如何反转掩码并创建将 1 表示为黑色而 0 表示为白色的二进制数组?
  • 其实反相可能是一个错误的术语,基本上我正在尝试创建一个数组,其中 1 为黑色,0 为白色
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-07-23
  • 2011-07-13
  • 1970-01-01
  • 2014-09-24
  • 2012-10-29
  • 1970-01-01
  • 2013-02-10
相关资源
最近更新 更多