您的位置:首页 > 财经 > 产业 > 苏州网站建设介绍_工业品牌设计公司_seo现在还有前景吗_网络营销公司简介

苏州网站建设介绍_工业品牌设计公司_seo现在还有前景吗_网络营销公司简介

2025/3/28 4:17:27 来源:https://blog.csdn.net/mengmengc/article/details/146509483  浏览:    关键词:苏州网站建设介绍_工业品牌设计公司_seo现在还有前景吗_网络营销公司简介
苏州网站建设介绍_工业品牌设计公司_seo现在还有前景吗_网络营销公司简介

裁剪完的影像可能会出现在文件夹中不显示的情况,试一试LZW压缩

import os
import numpy as np
from osgeo import gdaldef crop_images(image_path, output_dir, crop_size=256, overlap_ratio=0.25):"""专业影像裁剪函数(保留原始特性):param image_path: 输入影像路径:param output_dir: 输出目录:param crop_size: 裁剪尺寸:param overlap_ratio: 重叠比例"""# 初始化GDAL数据集ds = gdal.Open(image_path)if ds is None:raise RuntimeError(f"无法打开影像文件:{image_path}")# 获取元数据cols = ds.RasterXSizerows = ds.RasterYSizebands = ds.RasterCountdata_type = ds.GetRasterBand(1).DataTypegeo_transform = ds.GetGeoTransform()projection = ds.GetProjection()# 创建输出目录os.makedirs(output_dir, exist_ok=True)# 计算滑动窗口参数step_size = int(crop_size * (1 - overlap_ratio))tile_count = 0positions = []  # 记录每个tile的起始坐标# 开始裁剪流程for y in range(0, rows, step_size):for x in range(0, cols, step_size):# 计算实际裁剪窗口y_end = min(y + crop_size, rows)x_end = min(x + crop_size, cols)y_start = max(y_end - crop_size, 0)x_start = max(x_end - crop_size, 0)# 读取影像数据tile_data = np.stack([ds.GetRasterBand(b + 1).ReadAsArray(x_start, y_start, x_end - x_start, y_end - y_start)for b in range(bands)])# 跳过全黑区块(可选)if np.all(tile_data == 0):continue# 保存影像块output_path = os.path.join(output_dir, f"img_{tile_count:04d}.tif")save_geotiff(output_path,tile_data,(geo_transform[0] + x_start * geo_transform[1],  # 更新左上角Xgeo_transform[1],  # 横向分辨率geo_transform[2],  # 旋转参数geo_transform[3] + y_start * geo_transform[5],  # 更新左上角Ygeo_transform[4],  # 旋转参数geo_transform[5]),  # 纵向分辨率projection,data_type)positions.append((x_start, y_start))  # 记录坐标对应关系tile_count += 1print(f"影像裁剪完成:共生成 {tile_count} 个有效区块")return positions  # 返回坐标信息供标签裁剪使用def crop_labels(label_path, output_dir, positions, crop_size=256, threshold=128):"""专业标签裁剪函数(强制二值化):param label_path: 输入标签路径:param output_dir: 输出目录:param positions: 从影像裁剪获取的坐标列表:param crop_size: 必须与影像裁剪尺寸一致:param threshold: 二值化阈值"""# 初始化GDAL数据集ds = gdal.Open(label_path)if ds is None:raise RuntimeError(f"无法打开标签文件:{label_path}")# 验证标签尺寸if (ds.RasterXSize, ds.RasterYSize) != (gdal.Open(label_path).RasterXSize, gdal.Open(label_path).RasterYSize):raise ValueError("标签与影像尺寸不匹配")# 创建输出目录os.makedirs(output_dir, exist_ok=True)# 处理每个对应位置for idx, (x_start, y_start) in enumerate(positions):# 计算实际窗口x_end = x_start + crop_sizey_end = y_start + crop_size# 读取标签数据(强制使用最近邻采样)label_tile = ds.GetRasterBand(1).ReadAsArray(x_start, y_start,crop_size, crop_size,buf_type=gdal.GDT_Byte  # 强制8位深度)# 二值化处理(支持多种阈值方式)if threshold == 'otsu':from skimage.filters import threshold_otsuthresh_val = threshold_otsu(label_tile)binary_tile = np.where(label_tile > thresh_val, 255, 0).astype(np.uint8)else:binary_tile = np.where(label_tile >= threshold, 255, 0).astype(np.uint8)# 保存标签output_path = os.path.join(output_dir, f"label_{idx:04d}.tif")save_geotiff(output_path,binary_tile[np.newaxis, ...],  # 添加波段维度ds.GetGeoTransform(),ds.GetProjection(),gdal.GDT_Byte  # 强制8位输出)print(f"标签裁剪完成:共生成 {len(positions)} 个对应标签")def save_geotiff(output_path, array, geo_transform, projection, data_type):"""专业GeoTIFF保存函数:param output_path: 输出路径:param array: 三维数组(波段, 高, 宽):param geo_transform: 地理变换参数:param projection: 投影信息:param data_type: GDAL数据类型"""# 验证输入数据if len(array.shape) != 3:raise ValueError("输入数组必须是三维(波段, 高, 宽)")# 创建文件driver = gdal.GetDriverByName('GTiff')ds = driver.Create(output_path,xsize=array.shape[2],ysize=array.shape[1],bands=array.shape[0],eType=data_type)# 设置地理信息ds.SetGeoTransform(geo_transform)ds.SetProjection(projection)# 写入数据for band in range(array.shape[0]):ds.GetRasterBand(band + 1).WriteArray(array[band])# 刷新缓存ds.FlushCache()ds = Noneif __name__ == "__main__":# ================== 参数配置 ==================IMAGE_PATH = r"F:\数据集\ImageCai.tif"LABEL_PATH = r"F:\ClipImage0_255.tif"OUTPUT_BASE = r"F:\dataset100"# ================== 执行流程 ==================# 第一步:裁剪影像并获取坐标信息img_positions = crop_images(image_path=IMAGE_PATH,output_dir=os.path.join(OUTPUT_BASE, "images"),crop_size=256,overlap_ratio=0.25)# 第二步:使用相同坐标裁剪标签crop_labels(label_path=LABEL_PATH,output_dir=os.path.join(OUTPUT_BASE, "labels"),positions=img_positions,crop_size=256,threshold=128  # 可改为'otsu'自动计算阈值)# ================== 质量验证 ==================def validate_tile_pair(img_path, label_path):"""验证影像-标签对是否匹配"""img_ds = gdal.Open(img_path)label_ds = gdal.Open(label_path)# 验证地理坐标if img_ds.GetGeoTransform() != label_ds.GetGeoTransform():print(f"坐标不匹配:{os.path.basename(img_path)}")# 验证尺寸if (img_ds.RasterXSize, img_ds.RasterYSize) != (label_ds.RasterXSize, label_ds.RasterYSize):print(f"尺寸不匹配:{os.path.basename(img_path)}")# 验证标签二值性label_arr = label_ds.GetRasterBand(1).ReadAsArray()unique_values = np.unique(label_arr)if not set(unique_values).issubset({0, 255}):print(f"非二值标签:{os.path.basename(label_path)} 包含值 {unique_values}")# 示例验证第一个样本对validate_tile_pair(os.path.join(OUTPUT_BASE, "images", "img_0000.tif"),os.path.join(OUTPUT_BASE, "labels", "label_0000.tif"))

压缩影像

import os
import glob
import tifffile# 设置输入和输出文件夹路径
input_folder = r'F:dataset100\images'
output_folder = r'F:dataset100\YaSuoimages'# 确保输出文件夹存在
if not os.path.exists(output_folder):os.makedirs(output_folder)# 使用glob模块遍历文件夹中的所有TIFF图像
tiff_files = glob.glob(os.path.join(input_folder, '*.tif'))# 遍历每个文件进行压缩
for file_path in tiff_files:try:# 使用tifffile读取TIFF文件with tifffile.TiffFile(file_path) as tif:# 获取文件名(不带扩展名)file_name = os.path.basename(file_path).replace('.tif', '_compressed.tif')# 设置输出文件路径output_path = os.path.join(output_folder, file_name)# 使用tifffile.imwrite来保存图像并应用LZW压缩# 读取图像的第一张页面(假设图像是单页TIFF)image_data = tif.asarray()# 保存图像并应用LZW压缩tifffile.imwrite(output_path, image_data, compression='lzw')print(f"图像 {file_path} 已压缩并保存到 {output_path}")except Exception as e:print(f"处理文件 {file_path} 时出错: {e}")

检查影像标签是否是二值化

import os
import cv2
import numpy as npdef is_binary_image(image_path):try:image = cv2.imread(image_path, 0)if image is None:print(f"无法读取图像: {image_path}")return Falseunique_values = np.unique(image)return len(unique_values) == 2 and set(unique_values) == {0, 255}except Exception as e:print(f"处理图像 {image_path} 时出现错误: {e}")return Falsedef check_all_labels_in_folder(folder_path):binary_report = {}for filename in os.listdir(folder_path):if filename.endswith(('.png', '.jpg', '.tif')):file_path = os.path.join(folder_path, filename)result = is_binary_image(file_path)binary_report[filename] = resultreturn binary_reportif __name__ == "__main__":label_folder = r'F:\Truedataset100\labels'report = check_all_labels_in_folder(label_folder)for file, is_binary in report.items():if is_binary:print(f"{file} 是二值图像。")else:print(f"{file} 不是二值图像。")

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com