Skip to content

imread() didn't close the image file sometime #12342

Closed

Description

@akmalmzamri

I have a program where I read an image file (e.g. from a webcam), crop a face (if any) and save the cropped face into a new image file. The program will then delete the original image file. Here's the code:

import cv2
import os
import datetime

cam = cv2.VideoCapture(0)
while True:
    imagenames = []
    imagename = 'face'+str(datetime.datetime.now().strftime('%Y%m%d_%H%M%S'))+'.jpg'
    ret, frame = cam.read()
    cv2.imwrite(imagename, frame)
    
    img = cv2.imread(imagename)
    face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    
    n = 0
    for (x,y,w,h) in faces:
        img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
        crop_img = img[y:y+h, x:x+w]

        try:
            imagenames.append(str(n)+'_'+imagename)
            cv2.imwrite("img"+str(n)+'_'+imagename,crop_img)
            n=n+1
        except Exception, e:
            print e
            pass

    os.remove(imagename)  

Problem is, sometime the image is not properly closed. This cause the program to throw this error:
The process cannot access the file because it is being used by another process

opencv-python version: 3.4.2.17
OS: Windows 7
Python version: 2.7.15

Activity

  1. alalek commented on Aug 30, 2018

    @alalek
    Member

    Please provide minimal and complete reproducer (eliminate CascadeClassifier and camera access at least).

  2. akmalmzamri commented on Aug 30, 2018

    @akmalmzamri
    Author

    This code will occasionally reproduce the error:

    import cv2
    import os
    import datetime
    
    while True:
        imagename_src = "src_img.jpg"
        imagename_dest = 'to_be_deleted_'+str(datetime.datetime.now().strftime('%Y%m%d_%H%M%S'))+'.jpg'
        img = cv2.imread(imagename_src)
        cv2.imwrite(imagename_dest, img)
        img2 = cv2.imread(imagename_dest)
    
        os.remove(imagename_dest)
    
  3. added
    Hackathon
    on Jan 14, 2020
  4. tataganesh commented on Jan 24, 2020

    @tataganesh

    @akmalhakimi1991 Could you post the complete error stacktrace?

  5. karlphillip commented on Feb 2, 2020

    @karlphillip

    I would like to investigate this.

  6. karlphillip commented on Feb 3, 2020

    @karlphillip

    The result of my investigation is that this issue is no longer reproducible with the latest OpenCV on Windows 10:

    • I executed the sample code in Python multiple times and then let it run for about 2h and nothing happened.
    • Then I ported it to C++ and let this program run for another 2h and nothing happened.

    The source codes used for testing are available here:
    test_source_codes.zip

    The output of getBuildInformation() on both applications is the same:

    General configuration for OpenCV 4.2.0-dev =====================================
      Version control:               4.2.0-209-gbf2f7b0f8b
    
      Platform:
        Timestamp:                   2020-02-02T18:44:55Z
        Host:                        Windows 10.0.18362 AMD64
        CMake:                       3.16.2
        CMake generator:             Visual Studio 15 2017
        CMake build tool:            C:/Program Files (x86)/Microsoft Visual Studio/2017/Community/MSBuild/15.0/Bin/MSBuild.exe
        MSVC:                        1916
    
      CPU/HW features:
        Baseline:                    SSE SSE2 SSE3
          requested:                 SSE3
        Dispatched code generation:  SSE4_1 SSE4_2 FP16 AVX AVX2 AVX512_SKX
          requested:                 SSE4_1 SSE4_2 AVX FP16 AVX2 AVX512_SKX
          SSE4_1 (16 files):         + SSSE3 SSE4_1
          SSE4_2 (2 files):          + SSSE3 SSE4_1 POPCNT SSE4_2
          FP16 (1 files):            + SSSE3 SSE4_1 POPCNT SSE4_2 FP16 AVX
          AVX (5 files):             + SSSE3 SSE4_1 POPCNT SSE4_2 AVX
          AVX2 (30 files):           + SSSE3 SSE4_1 POPCNT SSE4_2 FP16 FMA3 AVX AVX2
          AVX512_SKX (6 files):      + SSSE3 SSE4_1 POPCNT SSE4_2 FP16 FMA3 AVX AVX2 AVX_512F AVX512_COMMON AVX512_SKX
    
      C/C++:
        Built as dynamic libs?:      YES
        C++ Compiler:                C:/Program Files (x86)/Microsoft Visual Studio/2017/Community/VC/Tools/MSVC/14.16.27023/bin/Hostx86/x64/cl.exe  (ver 19.16.27035.0)
        C++ flags (Release):         /DWIN32 /D_WINDOWS /W4 /GR  /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /Oi  /fp:precise     /EHa /wd4127 /wd4251 /wd4324 /wd4275 /wd4512 /wd4589 /MP8   /MD /O2 /Ob2 /DNDEBUG
        C++ flags (Debug):           /DWIN32 /D_WINDOWS /W4 /GR  /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /Oi  /fp:precise     /EHa /wd4127 /wd4251 /wd4324 /wd4275 /wd4512 /wd4589 /MP8   /MDd /Zi /Ob0 /Od /RTC1
        C Compiler:                  C:/Program Files (x86)/Microsoft Visual Studio/2017/Community/VC/Tools/MSVC/14.16.27023/bin/Hostx86/x64/cl.exe
        C flags (Release):           /DWIN32 /D_WINDOWS /W3  /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /Oi  /fp:precise       /MP8    /MD /O2 /Ob2 /DNDEBUG
        C flags (Debug):             /DWIN32 /D_WINDOWS /W3  /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /Oi  /fp:precise       /MP8  /MDd /Zi /Ob0 /Od /RTC1
        Linker flags (Release):      /machine:x64  /INCREMENTAL:NO
        Linker flags (Debug):        /machine:x64  /debug /INCREMENTAL
        ccache:                      NO
        Precompiled headers:         YES
        Extra dependencies:
        3rdparty dependencies:
    
      OpenCV modules:
        To be built:                 calib3d core dnn features2d flann gapi highgui imgcodecs imgproc ml objdetect photo python3 stitching ts video videoio
        Disabled:                    world
        Disabled by dependency:      -
        Unavailable:                 java js python2
        Applications:                tests perf_tests apps
        Documentation:               NO
        Non-free algorithms:         NO
    
      Windows RT support:            NO
    
      GUI:
        Win32 UI:                    YES
        VTK support:                 NO
    
      Media I/O:
        ZLib:                        build (ver 1.2.11)
        JPEG:                        build-libjpeg-turbo (ver 2.0.2-62)
        WEBP:                        build (ver encoder: 0x020e)
        PNG:                         build (ver 1.6.37)
        TIFF:                        build (ver 42 - 4.0.10)
        JPEG 2000:                   build (ver 1.900.1)
        OpenEXR:                     build (ver 2.3.0)
        HDR:                         YES
        SUNRASTER:                   YES
        PXM:                         YES
        PFM:                         YES
    
      Video I/O:
        DC1394:                      NO
        FFMPEG:                      YES (prebuilt binaries)
          avcodec:                   YES (58.54.100)
          avformat:                  YES (58.29.100)
          avutil:                    YES (56.31.100)
          swscale:                   YES (5.5.100)
          avresample:                YES (4.0.0)
        GStreamer:                   NO
        DirectShow:                  YES
        Media Foundation:            YES
          DXVA:                      YES
    
      Parallel framework:            Concurrency
    
      Trace:                         YES (with Intel ITT)
    
      Other third-party libraries:
        Intel IPP:                   2019.0.0 Gold [2019.0.0]
               at:                   C:/Users/kpbuhr/Documents/workspace/tmp/opencv_build/3rdparty/ippicv/ippicv_win/icv
        Intel IPP IW:                sources (2019.0.0)
                  at:                C:/Users/kpbuhr/Documents/workspace/tmp/opencv_build/3rdparty/ippicv/ippicv_win/iw
        Lapack:                      NO
        Eigen:                       NO
        Custom HAL:                  NO
        Protobuf:                    build (3.5.1)
    
      OpenCL:                        YES (NVD3D11)
        Include path:                C:/Users/kpbuhr/Documents/workspace/tmp/opencv/3rdparty/include/opencl/1.2
        Link libraries:              Dynamic load
    
      Python 3:
        Interpreter:                 C:/Program Files/Python-3.7.6-x64/python.exe (ver 3.7.6)
        Libraries:                   C:/Program Files/Python-3.7.6-x64/libs/python37.lib (ver 3.7.6)
        numpy:                       C:/Users/kpbuhr/AppData/Roaming/Python/Python37/site-packages/numpy/core/include (ver 1.18.1)
        install path:                C:/Program Files/Python-3.7.6-x64/Lib/site-packages/cv2/python-3.7
    
      Python (for build):            C:/Program Files/Python-3.7.6-x64/python.exe
    
      Java:
        ant:                         NO
        JNI:                         NO
        Java wrappers:               NO
        Java tests:                  NO
    
      Install to:                    C:/Users/kpbuhr/Documents/workspace/tmp/opencv_build/install
    
  7. karlphillip commented on Feb 4, 2020

    @karlphillip

    @asmorkalov I believe this issue can be closed. Is there anything else you would like me to do?

  8. asmorkalov commented on Feb 5, 2020

    @asmorkalov
    Contributor

    @karlphillip The best solution for the issue is to find commit that fixes the problem, but I'm not sure if it's possible for this particular case. Also the issue can be caused not by OpenCV itself, but antivirus software and search indexer process. I observed such issues with CI before. I think we can close the ticket till somebody reports the same problems.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Hackathonbugcategory: imgcodecsplatform: win32test

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions