How to read Image from Path and Convert to a NumPy Array in Python.

How to read Image from Path and Convert to a NumPy Array in Python.

Three methods to convert an image path to a NumPy array:

  1. Use OpenCV

    # OpenCV
    import cv2
    img = cv2.imread(image_path)   # reads an image in the BGR format
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)   # BGR -> RGB
    
  2. Use Matplotlib

    # Use Matplotlib
    from matplotlib.image import imread
    img = imread(image_path)
    
  3. Use PIL

    from PIL import Image
    img = Image.open(image_path)
    img = np.array(img)
    

The result below:

image.png