Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QFileDialog and OpenCV's imread()-Problem



  • Hi, guys,

    i want to create a code where i can select different images via a GUI. For this I use QFileFialog.getOpenFileNames(). After that I want to store the path of the image in a variable to display it with imread/imshow. But it only works if I use the path directly. As soon as I copy the path into a variable it does not work anymore. Can someone give me a hint ?

    def open_dialog_box(self):
            filename, _ = np.asarray(QFileDialog.getOpenFileNames(self, 'Select Multi File', 'default', 'All Files (*)'))
            for name in filename:
                #import pic
                pic = cv2.imread(name, cv2.IMREAD_ANYDEPTH) #This doesn't works
                **pic = cv2.imread("C:\\Users\\Image_name", cv2.IMREAD_ANYDEPTH)** #This works
                cv2.imshow("Window", pic)
    
    app = QApplication(sys.argv)
    w = Fenster()
    w.show()
    sys.exit(app.exec_())
    

    The bold line works. But I don't want to enter the whole path every time. I want the path to be automatically stored in a variable and then used to display the image. Is there a method to use a variable instead of typing the whole path ?


  • Banned

    @elias_hh here is a simple MUC (Minimal Usable Code) example that should help you with what you are trying to do however because you did not supply an MRE (Minimal Reproducible Example) that could be simply copied/pasted/ran -- I can not be sure you should always supply an MRE when asking questions like these as it helps us do you the favor you are requesting which is for us to help you with your issue

    from PyQt5.QtCore    import pyqtSlot
    #from PyQt5.QtWidgets import 
    from PyQt5.QtWidgets import QApplication, QWidget, QFileDialog, QHBoxLayout, QVBoxLayout
    from PyQt5.QtWidgets import QTextEdit, QPushButton
    
    class Form(QWidget):
        def __init__(self):
            QWidget.__init__(self)
            self.setWindowTitle('Get Pics')
    
            self.btnGetPic = QPushButton('Get Pic')
            self.btnGetPic.clicked.connect(self.GetPicDialog)
    
            HBox = QHBoxLayout()
            HBox.addStretch(1)
            HBox.addWidget(self.btnGetPic)
    
            self.txeImages = QTextEdit()
    
            VBox = QVBoxLayout()
            VBox.addWidget(self.txeImages)
            VBox.addLayout(HBox)
    
            self.setLayout(VBox)
    
        @pyqtSlot()
        def GetPicDialog(self):
          # K.I.S.S. it (Keep It Simple and Smart) do not add extra unnecessary functionality
          # the numpy method is not needed here you just need to understand the data you are
          # getting back the output to the GUI is meant to help you understand that data
          # import pic or list of pics
            Results = QFileDialog.getOpenFileNames(self, 'Select Multi File', 'default', 'All Files (*)')
            self.txeImages.append(str(Results))
            self.txeImages.append('******************************')
            PathFileList = Results[0]
            self.txeImages.append(str(PathFileList))
            self.txeImages.append('******************************')
            for PathFile in PathFileList:
              # Validate its the proper file type -- I used text files for my testing
                if '.txt' in PathFile:
                    self.txeImages.append(PathFile)
    # cv2 was not included so not sure what it is but PathFile should contain what you 
    # need now for the following to work
    #                Pic = cv2.imread(PathFile, cv2.IMREAD_ANYDEPTH)
    #                cv2.imshow('Window', Pic)
                else:
                    self.txeImages.append('***** Incorrect File Type :' + str(PathFile))
    
    if __name__ == "__main__":
        MainEventHandler = QApplication([])
    
        MainApplication = Form()
        MainApplication.show()
        
        MainEventHandler.exec()
    

  • Lifetime Qt Champion

    @elias_hh Hi and welcome to devnet,

    Since you are on Windows, I'll make an educated guess. Qt handles path in all platform using forward slashes so it makes the code easier to write cross-platform. My take is that OpenCV is not ready for that on Windows, therefore you should use QDir.toNativeSeparators before passing it to imread.


  • Banned

    @SGaist I do not have a problem with the forward slashes in a Windows environment even from the command line so I am not thinking that has anything to do with the issue -- but I could be wrong



  • @elias_hh said in QFileDialog and OpenCV's imread()-Problem:

    Please print out the name you are passing to cv2.imread(name, which you ultimately get via np.asarray(QFileDialog.getOpenFileNames()), so that you & we can compare it to the whatever cv2.imread("C:\\Users\\Image_name" you say works. Then we will know what the difference is.

    Which may be as @SGaist says. Or there is some other difference. My question would be take out the np.asarray(), try with filename, _ = QFileDialog.getOpenFileNames(self, 'Select Multi File', 'default', 'All Files (*)'). That returns a tuple in Python, and you are np.asarray()-ing that, so I'm not sure your filename is what you think it is? We'll know once you print out name.



  • @Denni-0 said in QFileDialog and OpenCV's imread()-Problem:

    I do not have a problem with the forward slashes in a Windows environment

    From this Python examples page for cv2.imread(), it seems to be the case since the examples looks like Windows paths (D: drive) with forward slashes

    img = cv2.imread('D:/image-1.png')
    

  • Lifetime Qt Champion

    I remember reading that recent versions of Windows (well the command line / power shell / maybe another one) improved the support for that. But the OP didn't say which one he is running.



  • @SGaist
    Once the OP just puts in print(name) we won't have to guess any more....



  • @JonB If i do print(name) then i get the following path like: C:/Users/Image_name . I think the problem is "/". Windows or OpenCV cant handle path with "/". If i use the same code with my macbook, it works fine.



  • @elias_hh
    If that's so, it looks like exactly what @SGaist suggested. If you are saying when you use a literal "C:\\Users\\Image_name" (i.e. value C:\Users\Image_name) it works but when you pass the result from QFileDialog.getOpenFileNames() which is C:/Users/Image_name it does not, then you have your difference/answer. cv2.imread(), does not appear to like forward slashes under Windows (forward slashes would be correctly native under Mac/Linux), though that seems to go against the example quoted by @Pablo-J-Rogina ....

    In any case, try what @SGaist suggested:

    nativeName = QDir.toNativeSeparators(name)
    pic = cv2.imread(nativeName, cv2.IMREAD_ANYDEPTH)
    

    Does that indeed now work?

    In any case, I would always use https://doc.qt.io/qt-5/qdir.html#toNativeSeparators when passing any Qt-generated path to anything non-Qt, unless the external documentation states it expects paths to be in forward-slash format.

    Under Windows each program can deal with paths with / vs \ differently. For example, the following two OS commands differ:

    dir \w
    dir /w
    

    The first lists a file named w in the root directory on the current drive (i.e. \w). The second lists files in the current directory, using the /w listing option.



  • Hi, guys,

    i apologize for the unnecessary confusion. the problem all along was not the back slash or the fordwar slash, but something completely different. I already mentioned that i get C:/Users/Image_name by using print(name). But apparently it has nothing to do with it. The bottom line is that the problem is the following:

    (Pre-information: my code is in the folder "GUI" and in "GUI" is also the folder with the images named "pics")

    when i select an image from this path C:/Users/Myname/Desktop/GUI/pics --> it doesn work, i become for pic = cv2.imread(name, cv2.IMREAD_ANYDEPTH) a print(pic) = none

    And here comes the weird part:

    when i select the same image from another path like: C:/Users/Myname/pics --> it works ! But i have realy no idea why.


  • Lifetime Qt Champion

    Any chances that your Windows is not in English ?



  • @SGaist i dont thing so



  • @elias_hh
    Show the actual paths printed out via the print(name), copied & pasted to here not typed in, of what does work and what does not.



  • @JonB Ok. I show you the print(name). This is the path, which doesnt work:

    C:/Users/hrezaie/Desktop/Hamid Rezaie/GUI/pics/mocim_FPLERW_3_3CM_10mm_MPW_6.0_für_Ex_Versuch1.bmp

    So, and if i choose the same image but from another path, it works. see here:

    C:/Users/hrezaie/Desktop/Hamid Rezaie/pics/mocim_FPLERW_3_3CM_10mm_MPW_6.0_für_Ex_Versuch1.bmp

    Again, to repeat. My Python code is in "GUI".



  • @elias_hh
    Then show me from a Command Prompt :

    dir "C:\Users\hrezaie\Desktop\Hamid Rezaie\GUI\pics\mocim_FPLERW_3_3CM_10mm_MPW_6.0_für_Ex_Versuch1.bmp"
    

    Please use copy & paste from what I have written. (In Command Prompt, right click should insert what you have copied to the clipboard, or click its menu in top-left-hand corner and Edit > Paste.)


  • Banned

    @elias_hh it would facilitate things greatly if you were to provide an MRE (Minimal Reproducible Example) of your issue that you are requesting the favor of us helping you with. This way we could easily just copy/paste -- set up test files -- run your code to get the same issue and then be able to diagnose what is actually going wrong or what might not be coded correctly

    Or you can continue with the current dialog and maybe solve this mysterious issue ;)

    If you need help with this MRE just post what you have and we can go from there


Log in to reply