自定义的图像操作库 mii

自定义的图像操作库 mii,放在 环境\Lib\site-packages
Anaconda3\envs\pytorch\Lib\site-packages\mii

mii
|——__init__.py
|——tools.py

__init__.py

from mii.tools import * 

tools.py:

import cv2
import torch
import numpy as np
from einops import rearrange


def imread(img_path, tensor=False, shape="hwc"):
    img = cv2.imread(img_path)
    img = bgr2rgb(img)
    img = np.array(img, dtype=np.float32)
    if tensor == True:
        img = ndarray2tensor(img)
    if shape == "chw":
        img = hwc2chw(img)
    return img


def imwrite(img, file_name):
    if type(img) == torch.Tensor:
        img = tensor2ndarray(img)
    img = np.array(img, dtype=np.uint8)
    img = bgr2rgb(img)
    cv2.imwrite(file_name, img)


def hwc2chw(img):
    if len(img.shape) == 3:
        img = rearrange(img, "h w c -> c h w")
    elif len(img.shape) == 4:
        img = rearrange(img, "b h w c -> b c h w")
    return img


def chw2hwc(img):
    if len(img.shape) == 3:
        img = rearrange(img, "c h w -> h w c")
    elif len(img.shape) == 4:
        img = rearrange(img, "b c h w -> b h w c")
    return img


def bgr2rgb(img):
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    return img


def ndarray2tensor(img, dytpe=torch.float32):
    img = torch.tensor(img, dtype=dytpe)
    return img


def tensor2ndarray(img, dtype=np.float32):
    img = img.cpu().detach().numpy()
    img = np.array(img, dtype=dtype)
    return img


def read_dir(dir, s=1, e=256,tensor=False, shape="hwc"):
    img_s = imread(f"{dir}/{s}.png")
    h,w,c = img_s.shape

    img_batch = np.zeros([e-s+1,h,w,c])
    for i in range(s, e + 1):
        img = imread(f"{dir}/{i}.png")
        if img.shape != img_s.shape:
            img = cv2.resize(img,[w,h],interpolation=cv2.INTER_CUBIC)
        img_batch[i-s] = img
    
    if tensor == True:
        img_batch = ndarray2tensor(img_batch)
    
    if shape == "chw":
        img_batch = hwc2chw(img_batch)
    
    return img_batch
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

什鲤子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值