Pillow转numpy数组

from PIL import Image
import numpy as np
import matplotlib.pyplot as plt

# PLT默认读取图片数据格式:(高,宽,通道(R,G,B))
im = Image.open('test.jpg')
print(im.size)

# 转numpy.ndarray格式
im_pillow= np.asarray(im)
print(im_pillow.shape)

# 赋值红色通道
im_pillow_c1_3ch = np.zeros(im_pillow.shape)
im_pillow_c1_3ch[:,:,0] = im_pillow[:,:,0]

# 赋值绿色通道
im_pillow_c2_3ch = np.zeros(im_pillow.shape)
im_pillow_c2_3ch[:,:,1] = im_pillow[:,:,1]

# 赋值蓝色通道
im_pillow_c3_3ch = np.zeros(im_pillow.shape)
im_pillow_c3_3ch[:,:,2] = im_pillow[:,:,2]

# 展示
plt.subplot(2,2,1)
plt.title("Origin Image")
plt.imshow(im_pillow)
plt.axis('off')

plt.subplot(2,2,2)
plt.title("Red Channel")
plt.imshow(im_pillow_c1_3ch.astype(np.uint8))
plt.axis('off')

plt.subplot(2,2,3)
plt.title("Green Channel")
plt.imshow(im_pillow_c2_3ch.astype(np.uint8))
plt.axis('off')

plt.subplot(2,2,4)
plt.title("Blue Channel")
plt.imshow(im_pillow_c3_3ch.astype(np.uint8))
plt.axis('off')

Pillow和OpenCV转numpy数组_pillow

OpenCV图片

OpenCV读入后顺序是BGR。

import cv2
im_cv2 = cv2.imread('test.jpg')

# opencv默认读取图片的数据为: (高,宽,通道(B,G,R))
im_cv2 = im_cv2[:,:,(2,1,0)] # 改变图像通道顺序为:RGB

print(type(im_cv2))
print(im_cv2.shape)

# 赋值红色通道
im_cv2_c1_3ch = np.zeros(im_cv2.shape)
im_cv2_c1_3ch[:,:,0] = im_cv2[:,:,0]

# 赋值绿色通道
im_cv2_c2_3ch = np.zeros(im_cv2.shape)
im_cv2_c2_3ch[:,:,1] = im_cv2[:,:,1]

# 赋值蓝色通道
im_cv2_c3_3ch = np.zeros(im_cv2.shape)
im_cv2_c3_3ch[:,:,2] = im_cv2[:,:,2]

# 展示
plt.subplot(2,2,1)
plt.title("Origin Image")
plt.imshow(im_cv2)
plt.axis('off')

plt.subplot(2,2,2)
plt.title("Red Channel")
plt.imshow(im_cv2_c1_3ch.astype(np.uint8))
plt.axis('off')

plt.subplot(2,2,3)
plt.title("Green Channel")
plt.imshow(im_cv2_c2_3ch.astype(np.uint8))
plt.axis('off')

plt.subplot(2,2,4)
plt.title("Blue Channel")
plt.imshow(im_cv2_c3_3ch.astype(np.uint8))
plt.axis('off')

Pillow和OpenCV转numpy数组_3c_02