Search code examples
pythonimagepython-imaging-libraryglob

How to load several images from the same folder?


I would like to load several images from the same folder. The code below is however yielding an error:

(TypeError Traceback (most recent call last)
<ipython-input-22-a30c12347c11> in <module>
2 import glob
3 
----> 4 image_list = map(Image.open, glob('/Users/name/images/*.jpg'))
5 
6 object_detection_api(image_list, rect_th=2, text_th=1, text_size=1)

TypeError: 'module' object is not callable)

I have already checked some trouble-shooting pages but the given notification keeps appearing. What do I have to amend in the code?

from PIL import Image
import glob

image_list = map(Image.open, glob('/Users/name/images/*.jpg'))

object_detection_api(image_list, rect_th=2, text_th=1, text_size=1)

As requested, I am pasting below the code for the object_detection_api as well:

def object_detection_api(img_path, threshold=0.7, rect_th=3, text_size=3, text_th=3):
  """
  object_detection_api
    parameters:
      - img_path - path of the input image
      - threshold - threshold value for prediction score
      - rect_th - thickness of bounding box
      - text_size - size of the class label text
      - text_th - thichness of the text
    method:
      - prediction is obtained from get_prediction method
      - for each prediction, bounding box is drawn and text is written
        with opencv
      - the final image is displayed
  """
  boxes, pred_cls = get_prediction(img_path, threshold)
  img = cv2.imread(img_path)
  img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
  for i in range(len(boxes)):
    cv2.rectangle(img, boxes[i][0], boxes[i][1],color=(0, 255, 0), thickness=rect_th)
    cv2.putText(img,pred_cls[i], boxes[i][0], cv2.FONT_HERSHEY_SIMPLEX, text_size, (0,255,0),thickness=text_th)
  plt.figure(figsize=(20,30))
  plt.imshow(img)
  plt.xticks([])
  plt.yticks([])
  plt.show()

Solution

  • Something like

    import os
    ls = [x for x in os.listdir('/Users/name/images/') if x.endswith('.jpg')]
    im_list = ['/Users/name/images/'+x for x in ls]
    for img_path in im_list:
       object_detection_api(img_path)
    

    May work for you.

    Keep in mind that map() and filter make generators, and if you need to eagerly evaluate them, you can call list() on them to put them in a list.

    Credit to @Gwang-JinKim for all the help!