3

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.

2
  • 1
    print type(img)? What does it say? Commented Jun 20, 2017 at 21:33
  • 1
    When you load an image, it returns an array containing (what appears to be) the RGB values of the pixels. I doubt any return contains information about the file itself. But, either explicitly or passed through a variable, you know the name of the file. Why do you need it returned? Commented Jun 20, 2017 at 21:37

1 Answer 1

13

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
Sign up to request clarification or add additional context in comments.

3 Comments

This returns the whole path with the image, is there a way to get only the file name?
@Ali123 what do you mean? Are you asking how to extract the file name from file path? Or did I misunderstand?
thanks for checking, i found a. way to extract file name using os.path.splitext(img)[0]. i am not sure if it's the best option but it works for now

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.