Python + OpenCV - Reading the image file name

断了今生、忘了曾经 提交于 2020-12-27 06:22:11

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/44663347/python-opencv-reading-the-image-file-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!