无法通过os.remove()删除文件,出现PermissionError:[WinError 32]

时间:2018-07-22 13:25:53

标签: python-3.x opencv

我使用python 3.6和opencv 3.4.0处理一些视频。 我的主要任务是检测视频中的上半身,并判断每帧中这些矩形的平均宽度是否足够大,如果太小,我将选择该视频。 这是我的代码。

# -*- coding:utf-8 -*-
import cv2
import glob as gb
import shutil
import os

cf2 = cv2.CascadeClassifier("C:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\Lib\site-packages\opencvhaartemp\haarcascades\haarcascade_mcs_upperbody.xml")


def renew(avw,count,w):
    return (count*avw+w)/(count+1)

def discern(img,avw,count,fps,size):
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    upperRects = cf2.detectMultiScale(
        gray, scaleFactor=1.2, minNeighbors=3, minSize=(50, 50))
    if len(upperRects):        
        for upperRect in upperRects:
            x, y, w, h = upperRect
            avw=renew(avw,count,w)
            cv2.rectangle(img, (x, y), (x + h, y + w), (0, 255, 0), 2)  # mark every body by rectangle       
    cv2.imshow("Image", img)
    return avw

video_path=gb.glob("D:\\onedrive\\codes\\spider\\opencv\\*avi")
for path in video_path:
    video = cv2.VideoCapture(path)

    fps = video.get(cv2.CAP_PROP_FPS)
    size = (int(video.get(cv2.CAP_PROP_FRAME_WIDTH)),int(video.get(cv2.CAP_PROP_FRAME_HEIGHT)))

    success, frame = video.read()
    avew=0.0
    count=0.0

    while success : #display frame by frame
        avew=discern(frame,avew,count,fps,size)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
        success, frame = video.read()
        count=count+1

    print("average width:",avew/size[0])
    if (avew/size[0]<0.2):
        cv2.destroyAllWindows()  # release windows
        os.remove(path)

然后我得到了以下错误信息

File "d:\onedrive\codes\spider\opencv\upper.py", line 68, in <module>
os.remove(path)
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process

我不知道如何释放要删除的视频占用的其他进程,甚至不知道哪个进程正在占用视频。

也请帮助我

cv2.destroyAllWindows()

如果这无法结束占用我要删除的视频的过程,那该怎么办?


我通过添加解决了问题

video.release()

在删除视频之前。

当我在VideoCapture异议中看到打开摄像机的演示时,突然想到可能需要释放视频异议,我发现编码器在关闭所有图像窗口之前先释放了VideoCapture异议。

1 个答案:

答案 0 :(得分:0)

尝试在删除文件之前删除VideoCapture对象。

del video
os.remove(path)