检测图像中物体的OpenCv任务

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

我正在尝试检测图像中的片段,如本 MATHLAB 示例所示。

我使用 openCV-library。

  import cv2
  import numpy as np
  from imutils.object_detection import non_max_suppression

  # Reading the image and the template
  img = cv2.imread('SourceImage.png')
  temp = cv2.imread('TargetFragment.png')
  # save the image dimensions
  W, H = temp.shape[:2]
  # Define a minimum threshold
  thresh = 0.4
  # Converting them to grayscale
  img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  temp_gray = cv2.cvtColor(temp, cv2.COLOR_BGR2GRAY)
  # Passing the image to matchTemplate method
  match = cv2.matchTemplate(
            image=img_gray, templ=temp_gray,
            method=cv2.TM_CCOEFF_NORMED)
  # Select rectangles with
  # confidence greater than threshold
  (y_points, x_points) = np.where(match >= thresh)
  # initialize our list of rectangles
   boxes = list()
  # loop over the starting (x, y)-coordinates again
  for (x, y) in zip(x_points, y_points):
             # update our list of rectangles
             boxes.append((x, y, x + W, y + H))
  # apply non-maxima suppression to the rectangles
  # this will create a single bounding box
  boxes = non_max_suppression(np.array(boxes))
  # loop over the final bounding boxes
  for (x1, y1, x2, y2) in boxes:
         # draw the bounding box on the image
         cv2.rectangle(img, (x1, y1), (x2, y2),
                   (255, 0, 0), 3)
  cv2.imwrite('result.png', img)

大图是:

enter image description here

要检测的目标片段是: enter image description here

但是检测到 2 个区域,而不是 1 个。该区域之一根本不包含目标片段: enter image description here

我错过了什么?

python opencv computer-vision
1个回答
0
投票

这对于 matchTemplate 来说不是一项艰巨的任务。 matchTemplate 更适合目标图像中存在几乎完全相同的模板副本的任务。

查看此答案以获取特征匹配的示例:如何使用 SURF 特征(Python OpenCV )匹配和对齐两个图像?

祝你好运!

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