ValueError: чтение закрытого файла в Python - PullRequest
0 голосов
/ 20 апреля 2020

Это программа:

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

Эта программа является частью Обнаружения шлема с использованием CNN, который я скачал с github: https://github.com/RajHarry/Automatic-Helmet-Detection-from-a-Bike-Rider

Эта программа работала несколько дней go. Но недавно я попытался запустить его и получил AttributeError:'PngImageFile' object has no attribute '_PngImageFile__frame ', который пропал при переустановке PIL, и теперь я получаю эту ошибку

1 Ответ

0 голосов
/ 22 апреля 2020

У моего друга была точно такая же проблема, и мы потратили некоторое время на ее устранение. Это проблема зависимостей. Я полагаю, что новые обновления подушки или imageio ломают что-то внутри лыжного мага.

На этой странице показаны требования лыжного мага: 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

Вы можете просто создать файл require.txt со строками чуть выше, а затем выполните команду pip install -r requirements.txt. Тогда это должно быть хорошо! Вы также можете обновить Skimage, набрав pip install --upgrade scikit-image, возможно, это тоже нужно сделать.

PS: Я думаю, что ошибка возникает из-за подушки или из-за imageio, скорее всего, не из numpy или из matplotlib ...

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...