python .tif 灰度图 转换为固定大小图像 方便算法识别

1、图像的类型的识别

2、使用opencv将图像进行转换

3、图像固定大小为 3704   2778

4、使用PIL与numpy 库都是不行唯有 opencv库可以

from PIL import Image
import cv2
from skimage import io
import numpy as np
# 图像类型判断  
def check_tif_mode(input_path):
    img = io.imread(input_path)
    if len(img.shape) == 2:
        print("图像可能是灰度图")
    elif img.shape[2] == 3:
        print("图像可能是RGB图")
    elif img.shape[2] == 4:
        print("图像可能是RGBA图")
    else:
        print("其他类型的图像")
def resize_and_pad_image_opencv(input_path, output_path):
    img = cv2.imread(input_path)
    if img is None:
        raise ValueError(f"无法读取图像:{input_path}")

    height, width = img.shape[:2]
    height, width = img.shape[:2]
    target_width = 3704
    target_height = 2778
    scale_x = target_width / width
    scale_y = target_height / height
    scale = min(scale_x, scale_y)

    new_width = int(width * scale)
    new_height = int(height * scale)
    resized_img = cv2.resize(img, (new_width, new_height), 
    interpolation=cv2.INTER_LINEAR)
    pad_top = (target_height - new_height) // 2
    pad_left = (target_width - new_width) // 2
    final_img = np.zeros((target_height, target_width, 3), dtype=np.uint8)
    final_img[pad_top:pad_top + new_height, pad_left:pad_left + new_width] = resized_img
    final_img = cv2.cvtColor(final_img, cv2.COLOR_BGR2GRAY)
    
    cv2.imwrite(output_path, final_img)


input_path = 'Macklin1-l.tif'
output_path = 'outMacklin1-l.tif'
resize_and_pad_image_opencv(input_path, output_path)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值