0

I've run into the problem that currently it is not possible to open Unicode path via OpenCV (4.1.1.26) in python 3.7. I'm trying to develop the best practice to do that.

When the path contains Unicode we should use something described here (u'D:\ö\handschuh.jpg' or '测试目录/test.jpg').

The first thing that I've tried to find is how to detect if a string contains Unicode. As I found here - all strings in python 3 are in Unicode.

For now, I'm using such workaround:

   import numpy as np
   import cv2
   def read(impath, flag=-1):
    try:
        image = cv2.imread(impath, flag)
        assert image is not None, ("Image is {im} check the path {path}".format (im=image, path=impath))
    except :
        image = cv2.imdecode(np.fromfile(impath, dtype=np.uint8), cv2.IMREAD_UNCHANGED)
        assert image is not None, ("Image is {im} check the path {path}".format(im=image, path=impath))

    return image

That is obviously not the best way to do that as you should never use try\except pattern.

What are the suggestions?

Eugene
  • 130
  • 3
  • 17
  • 2
    typo: if its currently _not_ impossible, why bother fixing it. Why should using try/except never be used? It is perfectly fine. – Patrick Artner Dec 09 '19 at 06:55
  • @PatrickArtner. Ok, thank you! As I know, it is not very good to use try\except as you may miss some exceptions during code execution. – Eugene Dec 09 '19 at 07:26
  • 1
    Well, the way that you are using it is wrong, because you don't specify any exception type but instead catch all of them, but using exception handling isn't per se wrong. That said, your question is lacking, what for example is `np`? In any case, why try the first method (which may fail) at all? – Ulrich Eckhardt Dec 09 '19 at 07:34
  • Oh, one more thing: You write that you tried to find out whether a string contains Unicode and that all strings in Python 3 do. What do you think "Unicode" is and how would you recognize it in a string? I think this may be one source of your misunderstanding. – Ulrich Eckhardt Dec 09 '19 at 07:39
  • @UlrichEckhardt, ok, thank you! How to specify it? I also added some examples of Unicode (u'D:\ö\handschuh.jpg' or '测试目录/test.jpg'). – Eugene Dec 09 '19 at 12:23

0 Answers0