zoukankan      html  css  js  c++  java
  • Python之使用PIL实现cv2

    有时候使用cv2需要安装opencv,但是opencv安装比较麻烦,因为需要编译过程。

    所以,我们可以使用PIL对cv2的一些常用接口进行复现。

     这里我们实现了cv2的imread(), imwrite(), resize(), cvtColor() 共四个接口。

    实现代码如下:

    import PIL
    from PIL import Image
    import numpy as np
    
    def imread(filename):
        img = np.array(Image.open(filename))
        if len(np.shape(img)) == 3:
            return img[:,:,::-1]
        else:
            return img
    
    def imwrite(filename, img):
        if len(np.shape(img)) == 3:
            img = Image.fromarray(img[:,:,::-1])
        else:
            img = Image.fromarray(img)
        img.save(filename)
    
    def resize(img,size, interpolation = PIL.Image.LANCZOS):
        # PIL.Image.NEAREST, PIL.Image.BILINEAR , PIL.Image.BICUBIC, PIL.Image.LANCZOS
        if len(np.shape(img)) == 3:
            return np.array(Image.fromarray(img[:,:,::-1]).resize(size,resample = interpolation))[:,:,::-1]
        else:
            assert len(np.shape(img)) == 2
            return np.array(Image.fromarray(img).resize(size,resample = interpolation))
    
    def cvtColor(img, mode):
        # mode: 'COLOR_BGR2GRAY', 'COLOR_GRAY2BGR'
        if mode == 'COLOR_BGR2GRAY':
            assert len(np.shape(img)) == 3
            img = Image.fromarray(img[:,:,::-1])
            return np.array(img.convert(mode = 'L'))
        if mode == 'COLOR_GRAY2BGR':
            assert len(np.shape(img)) == 2
            return np.repeat(img[:, :, np.newaxis], 3, axis=2)
            
    
        return None
  • 相关阅读:
    很难理解的三个设计模式
    设计模式思考(转)
    AOP
    CAP理论(摘)
    DDBS
    NoSql
    Enterprise Library 企业库
    padright padleft
    Process ProcessThread Thread
    053374
  • 原文地址:https://www.cnblogs.com/huangshiyu13/p/8475559.html
Copyright © 2011-2022 走看看