欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

详解Python Opencv和PIL读取图像文件的差别

时间:2021-01-21 10:52:13|栏目:Python代码|点击:

前言

之前在进行深度学习训练的时候,偶然发现使用PIL读取图片训练的效果要比使用python-opencv读取出来训练的效果稍好一些,也就是训练更容易收敛。可能的原因是两者读取出来的数据转化为pytorch中Tensor变量稍有不同,这里进行测试。

之后的代码都导入了:

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

测试

使用PIL和cv2读取图片时会有细微的区别,通过下面的代码可以发现两者读取图片是有区别的,也就是使用PIL读取出来的图片转为numpy格式和直接使用cv读取的图片在像素点上并不是完全一致:

In[11]: image = cv2.imread('datasets/0_target.jpg')
In[18]: image_pil = Image.open('datasets/0_target.jpg').convert('RGB')
In[19]: image_pil = np.array(image_pil)
In[20]: image_cv = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
In[21]: image_cv == image_pil
Out[21]: 
array([[[ True, True, False],
    [ True, False, False],
    [False, False, False],
    ...,
    [ True, True, True],
    [ True, True, True],
    [ True, True, True]],

    [[ True, True, False],
    [ True, True, True],
    [False, True, False],
    ...,
    [ True, True, False],
    [ True, True, True],
    [ True, True, True]],

    [[ True, True, False],
    [ True, True, True],
    [False, False, False],
    ...,
    [ True, True, True],
    [ True, True, True],
    [ True, True, False]],

    ...,

    [[ True, True, True],
    [ True, True, True],
    [ True, True, True],
    ...,
    [False, False, True],
    [ True, True, True],
    [False, False, False]],

    [[ True, True, True],
    [ True, True, True],
    [ True, True, True],
    ...,
    [ True, True, True],
    [ True, True, True],
    [False, False, False]],

    [[ True, False, False],
    [ True, False, False],
    [ True, False, False],
    ...,
    [ True, True, True],
    [False, False, False],
    [ True, False, False]]])
In[26]: image_cv.shape
Out[26]: (682, 700, 3)
In[27]: image_pil.shape
Out[27]: (682, 700, 3)
In[28]: image_pil - image_cv
Out[28]: 
array([[[ 0,  0,  1],
    [ 0, 255,  3],
    [255,  1,  2],
    ...,
    [ 0,  0,  0],
    [ 0,  0,  0],
    [ 0,  0,  0]],

    [[ 0,  0,  2],
    [ 0,  0,  0],
    [255,  0,  2],
    ...,
    [ 0,  0, 254],
    [ 0,  0,  0],
    [ 0,  0,  0]],

    [[ 0,  0,  2],
    [ 0,  0,  0],
    [255,  1,  2],
    ...,
    [ 0,  0,  0],
    [ 0,  0,  0],
    [ 0,  0, 254]],

    ...,

    [[ 0,  0,  0],
    [ 0,  0,  0],
    [ 0,  0,  0],
    ...,
    [254,  1,  0],
    [ 0,  0,  0],
    [ 1, 255,  3]],

    [[ 0,  0,  0],
    [ 0,  0,  0],
    [ 0,  0,  0],
    ...,
    [ 0,  0,  0],
    [ 0,  0,  0],
    [ 2, 254,  4]],

    [[ 0,  1, 253],
    [ 0,  1, 253],
    [ 0,  1, 255],
    ...,
    [ 0,  0,  0],
    [ 1, 254,  1],
    [ 0, 255,  2]]], dtype=uint8)

上一篇:Python3爬虫里关于Splash负载均衡配置详解

栏    目:Python代码

下一篇:Python 日期区间处理 (本周本月上周上月...)

本文标题:详解Python Opencv和PIL读取图像文件的差别

本文地址:http://www.codeinn.net/misctech/48691.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有