作业&练习

  • 检测各种多边形
  • 编写代码检测定位药丸
  • 实操课:
  • 相机标定
  • 车道线检测
  • 实时模板匹配
    • 找到目标并进行透视变换(恢复期望形状)
    • 查找指定物体(圈出目标区域)
  • 车道线检测(视频)

参考资源

处理封闭路径的备选函数:

  • 计算面积:cv2.contourArea(contour)
  • 计算周长:cv2.arcLength(curve, True)
  • 多边形逼近:cv2.approxPolyDP(curve, epsilon, True)
  • 判断是否是凸多边形:cv2.isContourConvex(contour)
  • 绘制封闭路径:cv2.cv.drawContours( img, contours, -1, (0, 255, 0), 3 )
  • 参数3为-1时:绘制所有contours轮廓
  • 参数3为>-1的n时:绘制contours[n]轮廓
  • 判断多边形边数:len(approxCurve)

  • 可直接通过len函数获取逼近后的多边形边数

  • 判断连续三个点连线构成的夹角:

def angle_cos(p0, p1, p2):
    d1, d2 = (p0-p1).astype('float'), (p2-p1).astype('float')
    return abs( np.dot(d1, d2) / np.sqrt( np.dot(d1, d1)*np.dot(d2, d2) ) )
  • 读取视频&导出视频

  • 读取

    import cv2
    import numpy as np
    
    # Create a VideoCapture object and read from input file
    # If the input is the camera, pass 0 instead of the video file name
    cap = cv2.VideoCapture('chaplin.mp4')
    
    # Check if camera opened successfully
    if (cap.isOpened()== False): 
      print("Error opening video stream or file")
    
    # Read until video is completed
    while(cap.isOpened()):
      # Capture frame-by-frame
      ret, frame = cap.read()
      if ret == True:
    
        # Display the resulting frame
        cv2.imshow('Frame',frame)
    
        # Press Q on keyboard to  exit
        if cv2.waitKey(25) & 0xFF == ord('q'):
          break
    
      # Break the loop
      else: 
        break
    
    # When everything done, release the video capture object
    cap.release()
    
    # Closes all the frames
    cv2.destroyAllWindows()
    
  • 写出

    import cv2
    import numpy as np
    
    # Create a VideoCapture object
    cap = cv2.VideoCapture(0)
    
    # Check if camera opened successfully
    if (cap.isOpened() == False): 
      print("Unable to read camera feed")
    
    # Default resolutions of the frame are obtained.The default resolutions are system dependent.
    # We convert the resolutions from float to integer.
    frame_width = int(cap.get(3))
    frame_height = int(cap.get(4))
    
    # Define the codec and create VideoWriter object.The output is stored in 'outpy.avi' file.
    out = cv2.VideoWriter('outpy.avi',cv2.VideoWriter_fourcc('M','J','P','G'), 10, (frame_width,frame_height))
    
    while(True):
      ret, frame = cap.read()
    
      if ret == True: 
    
        # Write the frame into the file 'output.avi'
        out.write(frame)
    
        # Display the resulting frame    
        cv2.imshow('frame',frame)
    
        # Press Q on keyboard to stop recording
        if cv2.waitKey(1) & 0xFF == ord('q'):
          break
    
      # Break the loop
      else:
        break  
    
    # When everything done, release the video capture and video write objects
    cap.release()
    out.release()
    
    # Closes all the frames
    cv2.destroyAllWindows()