ValueError:在Python中读取已关闭的文件

问题描述 投票:0回答:1

这是程序:

import cv2
import os
import numpy as np
from skimage.io import imread_collection

images = imread_collection('video_to_images/*.png')
print(images)
skip=0
ok = []
not_ok = []
sub_ele = 0
user_num = 0
first_num = 0
first_img = images[0]
newpath = 'Cluster_Dataset/user_'+str(user_num)
if not os.path.exists(newpath):
    os.makedirs(newpath)

cv2.imwrite(newpath+"/"+str(sub_ele)+'.png',cv2.cvtColor(first_img, cv2.COLOR_RGB2BGR))
sub_ele+=1
num=0
ok.append(num)
correct=0
print("*****************")
print("update number(first): ",num)
while(True):
    num += 1
    print("update number(second): ",num)
    if(num==len(images)):
        print("*******************\n")
        print("\n*******************")
        print("Done with 'Grouping_Images'")
        print("*******************")
        break
    second_img = images[num]
    # 1) Check if 2 images are equals
    if first_img.shape == second_img.shape:
        print("The images have same size and channels")
        difference = cv2.subtract(first_img, second_img)
        b, g, r = cv2.split(difference)
        if cv2.countNonZero(b) == 0 and cv2.countNonZero(g) == 0 and cv2.countNonZero(r) == 0:
            print("The images are completely Equal")
        else:
            print("The images are NOT equal")
    # 2) Check for similarities between the 2 images
    sift = cv2.xfeatures2d.SIFT_create()
    kp_1, desc_1 = sift.detectAndCompute(first_img, None)
    kp_2, desc_2 = sift.detectAndCompute(second_img, None)
    index_params = dict(algorithm=0, trees=5)
    search_params = dict()
    flann = cv2.FlannBasedMatcher(index_params, search_params)
    matches = flann.knnMatch(desc_1, desc_2, k=2)
    good_points = []
    ratio = 0.6
    for m, n in matches:
        if m.distance < ratio*n.distance:
            good_points.append(m)
    print("total good_points: ",len(good_points))
    if(len(good_points)>=10):
        print("correct number: ",num)
        cv2.imwrite(newpath+"/"+str(sub_ele)+'.png',cv2.cvtColor(second_img, cv2.COLOR_RGB2BGR))
        sub_ele+=1
        ok.append(num)
        correct=num
        skip+=1
        wrong_preds = 0
    else:
        wrong_preds += 1 
        skip+=1
        if(num not in ok):
            not_ok.append(num)
        if(wrong_preds>1):
            print("wrong preds: ",wrong_preds)
            print("total skips: ",skip)
            print("current number: ",num)
            print("user cluster is completed")
            print("ok list: ",ok)
            print("not_ok: ",not_ok)
            print("*******************")
            sub_ele = 0
            user_num+=1
            first_img = images[not_ok[0]]
            num = not_ok[0]
            print("update number(first): {}".format(num))
            not_ok = []
            newpath = 'Cluster_Dataset/user_'+str(user_num)
            if not os.path.exists(newpath):
                os.makedirs(newpath)
            cv2.imwrite(newpath+"/"+str(sub_ele)+'.png',cv2.cvtColor(first_img, cv2.COLOR_RGB2BGR))
            ok.append(num)
            sub_ele+=1
            skip=0
            wrong_preds = 0
        else:
            print("user cluster is 'not at completed'")
    #result = cv2.drawMatches(first_img, kp_1, second_img, kp_2, good_points, None)

    #cv2.imshow("result", result)
    #cv2.imshow("first_img", first_img)
    #cv2.imshow("Duplicate", second_img)
    #cv2.waitKey(0)
    #cv2.destroyAllWindows()

这是错误:

Traceback (most recent call last):
  File "C:\Users\QWERTY\Desktop\Automatic-Helmet-Detection-from-a-Bike-Rider\compare_two_images.py", line 6, in <module>
    images = imread_collection('video_to_images/*.png')
  File "C:\Users\QWERTY\AppData\Local\Programs\Python\Python36\lib\site-packages\skimage\io\_io.py", line 91, in imread_collection
    plugin=plugin, **plugin_args)
  File "C:\Users\QWERTY\AppData\Local\Programs\Python\Python36\lib\site-packages\skimage\io\manage_plugins.py", line 210, in call_plugin
    return func(*args, **kwargs)
  File "C:\Users\QWERTY\AppData\Local\Programs\Python\Python36\lib\site-packages\skimage\io\collection.py", line 391, in imread_collection
    load_func=imread)
  File "C:\Users\QWERTY\AppData\Local\Programs\Python\Python36\lib\site-packages\skimage\io\collection.py", line 186, in __init__
    self._numframes = self._find_images()
  File "C:\Users\QWERTY\AppData\Local\Programs\Python\Python36\lib\site-packages\skimage\io\collection.py", line 231, in _find_images
    im.seek(i)
  File "C:\Users\QWERTY\AppData\Local\Programs\Python\Python36\lib\site-packages\PIL\PngImagePlugin.py", line 748, in seek
    self._seek(f)
  File "C:\Users\QWERTY\AppData\Local\Programs\Python\Python36\lib\site-packages\PIL\PngImagePlugin.py", line 784, in _seek
    ImageFile._safe_read(self.fp, self.__prepare_idat)
  File "C:\Users\QWERTY\AppData\Local\Programs\Python\Python36\lib\site-packages\PIL\ImageFile.py", line 549, in _safe_read
    return fp.read(size)
ValueError: read of closed file

[该程序是我从github下载的使用CNN的头盔检测的一部分:https://github.com/RajHarry/Automatic-Helmet-Detection-from-a-Bike-Rider

该程序几天前正在运行。但是最近我尝试运行它,并得到一个AttributeError:'PngImageFile' object has no attribute '_PngImageFile__frame',当我重新安装PIL时它消失了,现在我遇到了此错误

python valueerror
1个回答
0
投票

我的朋友遇到了完全相同的问题,我们花了一些时间解决它。这是一个依赖的问题。我相信枕头或imageio的新更新正在打破skimage中的某些问题。

此页面显示了skimage的要求:https://scikit-image.org/docs/stable/install.html

她用pip install --force-reinstall scikit-image更新了所有软件包,所以我们查看了她的软件包“比我的版本高”的软件包,这是她必须执行的降级列表:

numpy==1.18.1
matplotlib==3.1.3
pillow==7.0.0
imageio==2.6.1

您可以仅使用上面的几行创建一个requirements.txt文件,然后运行命令pip install -r requirements.txt。那应该很好!您也可以通过运行pip install --upgrade scikit-image更新skimage,也许也需要这样做。

PS:我认为该错误来自枕头或图像,很可能不是numpy或matplotlib ...

© www.soinside.com 2019 - 2024. All rights reserved.