How to Read a Image in Python

Posted by yaohong on Saturday, January 23, 2021

TOC

How to Read a Image in Python

There are three ways to read a image, the codes is showing below.


image_path = "fasterRCNN/faster-rcnn-keras-master/img/street.jpg";

from PIL import Image
import numpy as np
image = Image.open(image_path) # RGB
tmp_image = np.array(image)
print("PIL open shape:",tmp_image.shape, tmp_image)


# load with cv2
import cv2
image = cv2.imread(image_path)  # mode: BGR
print("cv2 imread shape:", image.shape) # (width,height,channel)


# load with matplotlib
import matplotlib.image as mpimg
image = mpimg.imread(image_path) #  mode: RGB
print("matplotlib imread shape:",image.shape, image) # ( height, width,channel(RGB) )

If you use cv2 to load a image , then show it with matplotlib, you should convert the image to RGB mode, this is because cv2 read a image in BGR mode, while matplotlib presents the image in RGB mode;

For example:

import cv2
image = cv2.imread(image_path)  # mode: BGR
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # BGR to RGB

from matplotlib import pyplot as plt
plt.imshow(image) # it will present normally.
plt.show()

「点个赞」

Yaohong

点个赞

使用微信扫描二维码完成支付