这是我的代码。
import cv2
import numpy as np
from copy import deepcopy
class Video:
def __init__(self, path):
self.name = path.split('/')[-1]
self.cap = cv2.VideoCapture(path)
当我创建一个 Video 类的实例并尝试对其进行深度复制时,出现此错误。
video = Video('video.mp4')
print(video)
print(deepcopy(video))
错误:
<main.Video object at 0x103496630> Traceback (most recent call last): File "test.py", line 28, in print(deepcopy(video)) File "/Users/tigranfahradyan/.local/share/virtualenvs/pyvideoproc-x3IHrdzn/lib/python3.7/copy.py", line 180, in deepcopy y = _reconstruct(x, memo, *rv) File "/Users/tigranfahradyan/.local/share/virtualenvs/pyvideoproc-x3IHrdzn/lib/python3.7/copy.py", line 280, in _reconstruct state = deepcopy(state, memo) File "/Users/tigranfahradyan/.local/share/virtualenvs/pyvideoproc-x3IHrdzn/lib/python3.7/copy.py", line 150, in deepcopy y = copier(x, memo) File "/Users/tigranfahradyan/.local/share/virtualenvs/pyvideoproc-x3IHrdzn/lib/python3.7/copy.py", line 240, in _deepcopy_dict y[deepcopy(key, memo)] = deepcopy(value, memo) File "/Users/tigranfahradyan/.local/share/virtualenvs/pyvideoproc-x3IHrdzn/lib/python3.7/copy.py", line 169, in deepcopy rv = reductor(4) TypeError: can't pickle cv2.VideoCapture objects
但是当我删除“cv2.VideoCapture(path)”时,一切正常。
import cv2
import numpy as np
from copy import deepcopy
class Video:
def __init__(self, path):
self.name = path.split('/')[-1]
输出:
<main.Video object at 0x10d0f7c18> <main.Video object at 0x119693eb8>
最佳答案
我有点想出了解决这个问题的方法,但我确信这不是最好的方法。由于某些原因,当您尝试深度复制字段设置为“cv2.VideoCapture(path_to_video)”的类的实例时,它会出错。
但是你可以有这样的局部变量。
import cv2
class Test:
def __init__(self):
cap = cv2.VideoCapture(path_to_video)
"""This will probably give an error for you
if you try to deepcopy the instance of this class"""
# self.cap = cv2.VideoCapture(path_to_video)
关于 python 3。当我在 __init__ 方法中深度复制具有 cv2.VideoCapture 的类的实例时出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55279979/