cv2 imread resize imwrite 函数

"""
doc
"""
import os.path

import numpy as np
import cv2


def cv_imread(file_path: str, look: bool = False) -> any:
    """
    read from imgpath to ndarray
    :param file_path:
    :param look:
    :return:
    """
    with open(file_path, 'rb') as f:
        fread = f.read()
        fread_np = np.frombuffer(fread, np.uint8)
        # fread_np = np.fromfile(file_path, np.uint8)
        img_decode = cv2.imdecode(fread_np, cv2.IMREAD_COLOR)
        if look:
            print(f"max:{np.max(img_decode)} in func cv_imread")
            cv2.imshow("img", img_decode)
            cv2.waitKey(3000)
    return img_decode


def cv_resize(src: np.ndarray, scale_percent: list[int], look: bool = False) -> np.ndarray:
    """
    cv_resize
    :param src:
    :param scale_percent: (50, 50)
    :param look:
    :return:
    """
    # scale
    scale_percent[1] = min(max(1, scale_percent[1]), 100)
    scale_percent[0] = min(max(1, scale_percent[0]), 100)
    print(f"width : {scale_percent[1]} %, height : {scale_percent[0]} %")

    # calculate the 50 percent of original dimensions
    width = int(src.shape[1] * scale_percent[1] / 100)
    height = int(src.shape[0] * scale_percent[0] / 100)

    # dsize
    dsize = (width, height)

    # resize image
    output = cv2.resize(src, dsize)
    if look:
        print(f"max:{np.max(output)} in func cv_resize")
        cv2.imshow("img", output)
        cv2.waitKey(3000)

    return output


def cv_imwrite(src: np.ndarray, save_path: str, look: bool = False) -> int:
    """
    np.ndarray to save_path
    :param src:
    :param save_path:
    :param look:
    :return:
    """
    img_type = "." + save_path.split(".")[-1]
    img_encode = cv2.imencode(img_type, src)[1]
    data_encode = np.array(img_encode)
    # look
    if look:
        print(f"max:{np.max(data_encode)} in func cv_imwrite")
        cv2.imshow("img", output)
        cv2.waitKey(3000)

    byte_encode = data_encode.tobytes()
    # dir_path
    if not os.path.exists(os.path.dirname(save_path)):
        return -1
    # 缓存数据保存到本地,以txt格式保存
    with open(save_path, 'wb') as f:
        f.write(byte_encode)
    return 0


def test_cv_imread():
    import time
    file_path = r"F:\python_code\20221225_python_gui\res\about.png"
    start_time = time.time()
    img_1 = cv_imread(file_path)
    assert img_1.shape[2] == 3
    print(img_1.shape, time.time() - start_time)

    start_time = time.time()
    img_2 = cv2.imread(file_path)
    print(np.max(img_2))
    print(img_2.shape, time.time() - start_time)


def test_cv_resize():
    file_path = r"F:\python_code\20221225_python_gui\res\python.png"
    src = cv_imread(file_path)
    output = cv_resize(src, [70, 70])
    assert type(output) == np.ndarray


def test_cv_imwrite():
    file_path = r"F:\python_code\20221225_python_gui\res\about.png"
    src = cv_imread(file_path)
    output = cv_resize(src, [70, 70])
    ret = cv_imwrite(output, file_path.split(".")[0] + "_1.png")
    assert ret == 0


if __name__ == "__main__":
    test_cv_imread()
    test_cv_resize()
    test_cv_imwrite()


好久没用了,要用,重新学习一把,分享一下。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值