栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python 读取图像(cv2,PIL,subplot)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python 读取图像(cv2,PIL,subplot)

  1. function:用cv2 读取、显示、保存 图像
  2. c2.read->按照bgr读取->show->可以正常显示bgr->write->把bgr转成rgb才会写入
  3. plot 显示的是rgb
  4. https://www.qianbo.com.cn/Tool/Rgba/ rgb对应颜色查询
import cv2
import matplotlib.pyplot as plt
import numpy as np
def show_img_cv2(rgb,window_name = 'bgr'):
    cv2.namedWindow(window_name, cv2.WINDOW_AUTOSIZE)#cv2.WINDOW_NORMAL:用户可以改变这个窗口大小  cv2.WINDOW_AUTOSIZE:窗口大小自动适应图片大小,并且不可手动更改
    cv2.imshow(window_name,rgb),cv2.waitKey()

def get_img_cv2(img_path):
    bgr = cv2.imread(img_path)#如果读取成功,返回(h,w,c)的bgr图片!!,即使你在目录下看到的是rgb,但它读取过来自动转化为bgr
    if bgr is None:
        print('cv2 get ', img_path.split('\')[-1], ' failed! ',end='')
        raise Exception('maybe there are something wrong with path!')
        #return
    return bgr
def save_img_cv2(path,bgr):
    try:
        succ = cv2.imwrite(path, bgr)#只能保存 BGR 3通道图像
        if succ == False:
            print('check the path!',end=' ');
            raise NameError()
    except Exception:
        print('save img failed!')

def plt_img(img):
    plt.figure()
    plt.imshow(img)
    plt.show()#注意,plt需要的img格式为rgb
    #plt.savefig('plt_fig.png')



path = r'‪C:Users13361PicturesCamera Rollmac.jpg'
bgr = get_img_cv2(path)#取出(h,w,3)的数组

1. 用cv2读取出来的数组是bgr格式的,使用cv2.imshow显示
show_img_cv2(bgr)

2. pyplot是用rgb格式显示的,直接显示在cv2得到的图像会出错
plt_img(bgr)

3. 把bgr格式转化为rgb
rgb = cv2.cvtColor(bgr,cv2.COLOR_BGR2RGB)
show_img_cv2(rgb,'rgb')
plt_img(rgb)

4. cv2.imwrite(img), img必须是bgr格式,否则图片会出错
save_img_cv2(r'..datargb.png',rgb)
save_img_cv2(r'..databgr.png',bgr)

5. PIL包处理图像,Image.open(path)读取出来的是一个图像对象,而不是数组
def get_img_PIL(path):
    from PIL import Image
    try:
        img_obj = Image.open(path)#这是一个Image对象(RGB), 直接对图像进行操作,而不是数组
        #img_obj.show()
        #img = np.asarray(img_obj)#转化为数组
        #img_obj = Image.fromarray(np.uint8(img))#从数组转化为Image对象
        #img_obj.save('')#保存路径
        return img_obj
    except Exception:
        print('PIL op failed!')
img_obj = get_img_PIL(path)
img_obj.show()
img = np.asarray(img_obj)
img.shape
(2124, 2070, 3)
img_obj = Image.fromarray(np.uint8(img))#从数组转化为Image对象

img_obj.save(path)#保存路径

6. subplot
def subpolt(img_dict,row = 1,column = 3):
    plt.figure()
    for k,(name,img) in enumerate(img_dict.items()):
        subplot = plt.subplot(row, column, k+1)#第三个参数代表第几个图像,从1开始
        plt.imshow(img)  # 通过for循环逐个显示图像
        subplot.set_title(name)
        plt.xticks([])  # 去掉x轴的刻度
        plt.yticks([])  # 去掉y轴的刻度
    plt.show()

img_dict = {'bgr(read from cv2)':bgr,'rgb':rgb, 'Image from PIL':img_obj,}
subpolt(img_dict,row = 1,column = 3)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1026427.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号