Search code examples
pythonopencvimread

Python + OpenCV - Reading the image file name


I have the following code snippet:

img = cv2.imread('1.jpg')

When I print img, I get the result shown below. How can I return the 1.jpg part only?

[[[140 149 139]
  [153 162 152]
  [155 165 153]
  ..., 
  [ 44  20   8]
  [ 46  22  10]
  [ 46  22  10]]

 [[151 160 150]
  [156 165 155]
  [152 162 150]
  ..., 
  [ 47  23  11]
  [ 48  24  12]
  [ 45  21   9]]

 [[155 164 154]
  [152 161 151]
  [146 156 144]
  ..., 
  [ 47  23  11]
  [ 49  25  13]
  [ 49  25  13]]

 ..., 
 [[ 28  16   6]
  [ 33  21  11]
  [ 32  20  10]
  ..., 
  [144 131 105]
  [150 137 111]
  [151 138 112]]

 [[ 33  18   9]
  [ 34  19  10]
  [ 34  20   8]
  ..., 
  [144 135 108]
  [143 134 107]
  [148 139 112]]

 [[ 31  16   7]
  [ 31  16   7]
  [ 35  21   9]
  ..., 
  [145 141 112]
  [137 133 105]
  [143 139 111]]]

Thanks.


Solution

  • I believe cv2.imread returns a numpy array. So, there is no way to store the name unless you use a custom class.

    class MyImage:
        def __init__(self, img_name):
            self.img = cv2.imread(img_name)
            self.__name = img_name
    
        def __str__(self):
            return self.__name
    

    Then, you can use this as:

    >>> x = MyImage('1.jpg')
    >>> str(x)
    1.jpg
    >>> x.img # the numpy array