python中不同库读取图片的格式不同

文章目录

  • 1. 图片的长度和宽度的获取方式不同
  • 2. 图片的类型不同

1. 图片的长度和宽度的获取方式不同

  • cv2:

  • PIL.Image:

  • skimage.io:

# coding: utf-8


from PIL import Image
import cv2
from skimage import io

def shape_size():
    img = cv2.imread('resize.jpg')
    print(img.shape)  # h, w, c
    print('cv2', type(img))
    img1 = Image.open('resize.jpg')
    print(img1.size)  # w, h
    print('PIL.Image', type(img1))
    img2 = io.imread('resize.jpg')
    print(img2.shape)  # h, w, c
    print('skimage.io', type(img2))


if __name__ == '__main__':
    shape_size()


(269, 154, 3)
cv2
(154, 269)
PIL.Image
(269, 154, 3)
skimage.io

2. 图片的类型不同

PIL.Image转换成OpenCV格式:

import cv2
from PIL import Image
import numpy as np
import os

file_name = '1.jpg'

root_image = 'test/image/'
img_path = os.path.join(root_image, file_name)
image = Image.open(img_path)
print(type(image))
print(type(np.asarray(image)))
img = cv2.cvtColor(np.asarray(image), cv2.COLOR_RGB2BGR)
print(type(img))

“”"



“”"

OpenCV转换成PIL.Image格式:

import cv2
from PIL import Image
import numpy as np
import os

file_name = '1.jpg'

root_image = 'test/image/'
img_path = os.path.join(root_image, file_name)

img = cv2.imread(img_path)
print(type(img))
image = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
print(type(image))

“”"


“”"

你可能感兴趣的:(计算机视觉,opencv)