遇到cv2.findContours()函数问题

时间:2017-01-28 15:44:04

标签: python-2.7 opencv image-processing opencv-contour

我无法使用此视频找到轮廓并在其周围绘制一个矩形。 链接:http://www.filedropper.com/outcutscaled

最初,我尝试通过简单地使用函数cv2.findContours()来查找轮廓,但它显示了一些点。然后我尝试应用一些形态变换,但由于轮廓不合适仍然没有运气。

你能告诉我我做错了什么吗?

P.S我正在使用cv2.bitwise_and()来消除阴影。也可以使用cv2.bitwise_or()

这是我的代码:

import cv2

def diffImg(t0, t1, t2):
  d1 = cv2.absdiff(t2, t1)
  d2 = cv2.absdiff(t1, t0)
  return cv2.bitwise_and(d1, d2)

cam = cv2.VideoCapture('out_cut_scaled.mp4')
fgbg = cv2.BackgroundSubtractorMOG2(history=50, varThreshold=50)
winName = "Movement Indicator"
cv2.namedWindow(winName, cv2.CV_WINDOW_AUTOSIZE)

# Read three images first:
t_minus = cv2.cvtColor(cam.read()[1], cv2.COLOR_RGB2GRAY)
t = cv2.cvtColor(cam.read()[1], cv2.COLOR_RGB2GRAY)
t_plus = cv2.cvtColor(cam.read()[1], cv2.COLOR_RGB2GRAY)

while True:
  result=diffImg(t_minus, t, t_plus)

  #frame = cv2.resize(result, (20, 20))
  #fgmask = result
  fgmask = cv2.blur(result, (10, 10))
  fgmask = fgbg.apply(fgmask)
  fgmask = cv2.medianBlur(fgmask, 7)



  #ret, thresh = cv2.threshold(result, 127, 255, 0)
  thresh = cv2.dilate(fgmask, None, iterations=2)
  #thresh = cv2.erode(thresh, None, iterations=2)
  """
  contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
  #cv2.drawContours(thresh, contours, -1, (0, 255, 0), 3)


  for contour in contours:
      x, y, w, h = cv2.boundingRect(contour)
      if w > 10 and h > 10:
          cv2.rectangle(thresh, (x, y), (x + w, y + h), (0, 255, 0), 2)
          print len(contours)
  """
  cv2.imshow(winName, thresh)
  cv2.imshow("frame", t)

  # Read next image
  t_minus = t
  t = t_plus
  t_plus = cv2.cvtColor(cam.read()[1], cv2.COLOR_RGB2GRAY)

  key = cv2.waitKey(10)
  if key == 27:
    cv2.destroyWindow(winName)
    break

OpenCV版本:2.4.13

Python版本:2.7

1 个答案:

答案 0 :(得分:1)

函数cv2.findContours(...)修改输入图像并将轮廓绘制为图像中的点。也许这就是为什么你只得到点。

要获得完整的轮廓,请使用厚度设置为某个高值的cv2.drawContours(...)和线型为8。