模块“cv2.cv2”没有属性“cv”

天才灵*_*才灵丹 5 python opencv

import cv2 
import numpy as np
cap = cv2.VideoCapture('1.MP4')
fourcc = cv2.FOURCC(*'XVID')
out  = cv2.videoWriter('output.avi',fourcc,20.0,(640,480))

while (1):
  #Capture frame-by-frame
  #ret = cap.set(3,960),cap.set(4,720)
  ret, frame = cap.read()
  if ret == True:
      frame = cv2.flip(frame,0)
      out.write(frame)

      cv2.imshow('frame',frame)

      if cv2.waitKey(1) == ord('q'):
          break
  else:
      break

cap.release()
out.release()
cv2.destroyAllWindows()
Run Code Online (Sandbox Code Playgroud)

如上所示,这是opencv文档中的demo,在我的电脑上可以运行。像这样的回溯:

Traceback (most recent call last):
  File "E:\opencv\Pic\test.py", line 34, in <module>
    fourcc = cv2.cv.FOURCC(*'XVID')
AttributeError: module 'cv2.cv2' has no attribute 'cv'
Run Code Online (Sandbox Code Playgroud)

我还看到了一些解决方案,例如将 cv2.cv 更改为 cv2 ,而回溯如下:

Traceback (most recent call last):
  File "E:\opencv\Pic\test.py", line 34, in <module>
    fourcc = cv2.FOURCC(*'XVID')
AttributeError: module 'cv2.cv2' has no attribute 'FOURCC'
Run Code Online (Sandbox Code Playgroud)

我非常感谢任何热心的解决方案来解决我的问题。

Kin*_*t 金 3

链接@Spence wetjen 帖子适用于旧版 OpenCV,在 OpenCV 3.x 中不起作用。

这是我的代码:


环境:Python3 + OpenCV 3.3

#!/usr/bin/python3
import cv2

## opening videocapture
cap = cv2.VideoCapture(0)

## some videowriter props
sz = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),
        int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))

fps = 20
#fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
#fourcc = cv2.VideoWriter_fourcc('m', 'p', 'e', 'g')
fourcc = cv2.VideoWriter_fourcc(*'mpeg')

## open and set props
vout = cv2.VideoWriter()
vout.open('output.mp4',fourcc,fps,sz,True)

cnt = 0
while cnt<20:
    cnt += 1
    print(cnt)
    _, frame = cap.read()
    cv2.putText(frame, str(cnt), (10, 20), cv2.FONT_HERSHEY_PLAIN, 1, (0,255,0), 1, cv2.LINE_AA)
    vout.write(frame)

vout.release()
cap.release()
Run Code Online (Sandbox Code Playgroud)

结果: