"""栅格数学与 GeoTIFF 读写。""" import math import numpy as np import shapely import tifffile from . import config def percentile_thresholds_from_values(values, percent_steps): sorted_values = np.sort(np.asarray(values, dtype=np.float32))[::-1] sorted_values = sorted_values[np.isfinite(sorted_values)] if sorted_values.size == 0: return [] thresholds = [] for percent in percent_steps: index = max(0, math.ceil(sorted_values.size * percent)) index = min(index, sorted_values.size - 1) thresholds.append(float(sorted_values[index])) return thresholds def ranked_pixel_rgb_for_values(values, data_mask, colors, percent_steps): result = np.zeros((*values.shape, 3), dtype=np.uint8) valid_positions = np.flatnonzero(data_mask.ravel()) if valid_positions.size == 0: return result, [], [] if len(percent_steps) != len(colors) - 1: raise ValueError("颜色数量必须比分位阈值数量多 1") valid_values = values.ravel()[valid_positions] thresholds = percentile_thresholds_from_values(valid_values, percent_steps) flat_result = result.reshape(-1, 3) remaining = np.ones(valid_values.shape, dtype=bool) rank_counts = [] for color, threshold in zip(colors[:-1], thresholds): selected = remaining & (valid_values > threshold) flat_result[valid_positions[selected]] = color rank_counts.append(int(np.count_nonzero(selected))) remaining &= ~selected flat_result[valid_positions[remaining]] = colors[-1] rank_counts.append(int(np.count_nonzero(remaining))) return result, thresholds, rank_counts def ranked_pixel_rgb_for_values_with_thresholds(values, data_mask, colors, thresholds): result = np.zeros((*values.shape, 3), dtype=np.uint8) valid_positions = np.flatnonzero(data_mask.ravel()) if valid_positions.size == 0: return result, [] if len(thresholds) != len(colors) - 1: raise ValueError("颜色数量必须比分位阈值数量多 1") valid_values = values.ravel()[valid_positions] flat_result = result.reshape(-1, 3) remaining = np.ones(valid_values.shape, dtype=bool) rank_counts = [] for color, threshold in zip(colors[:-1], thresholds): selected = remaining & (valid_values > threshold) flat_result[valid_positions[selected]] = color rank_counts.append(int(np.count_nonzero(selected))) remaining &= ~selected flat_result[valid_positions[remaining]] = colors[-1] rank_counts.append(int(np.count_nonzero(remaining))) return result, rank_counts def smooth_rgb_inside_mask(rgb, data_mask, radius): if radius <= 0: return rgb weight = data_mask.astype(np.float32) blurred_weight = gaussian_blur(weight, radius) smoothed = np.zeros_like(rgb, dtype=np.float32) for channel in range(3): blurred_channel = gaussian_blur(rgb[..., channel].astype(np.float32) * weight, radius) np.divide(blurred_channel, blurred_weight, out=smoothed[..., channel], where=blurred_weight > 0) smoothed[~data_mask] = 0 return np.clip(smoothed, 0, 255).astype(np.uint8) def gaussian_kernel(radius): if radius <= 0: return np.array([1.0], dtype=np.float32) sigma = max(radius / 2.0, 0.1) x = np.arange(-radius, radius + 1, dtype=np.float32) kernel = np.exp(-(x * x) / (2.0 * sigma * sigma)) return kernel / kernel.sum() def validate_smoothing_radius(name, radius): if isinstance(radius, bool) or not isinstance(radius, int) or radius < 0: raise ValueError(f"{name} 必须是非负整数") def convolve_axis(array, kernel, axis): if kernel.size == 1: return array radius = kernel.size // 2 pad_width = [(0, 0)] * array.ndim pad_width[axis] = (radius, radius) padded = np.pad(array, pad_width, mode="edge") windows = np.lib.stride_tricks.sliding_window_view(padded, kernel.size, axis=axis) return (windows @ kernel).astype(np.float32, copy=False) def gaussian_blur(array, radius): kernel = gaussian_kernel(radius) blurred = convolve_axis(array.astype(np.float32), kernel, axis=0) return convolve_axis(blurred, kernel, axis=1) def to_float(value): if value is None: return None if isinstance(value, (int, float)): number = float(value) return number if math.isfinite(number) else None try: text = str(value).strip() if not text: return None number = float(text) if not math.isfinite(number): return None return number except ValueError: return None def geotiff_extratags(minx, maxy, pixel_width, pixel_height): model_pixel_scale = (pixel_width, pixel_height, 0.0) model_tiepoint = (0.0, 0.0, 0.0, minx, maxy, 0.0) geo_key_directory = ( 1, 1, 0, 4, 1024, 0, 1, 2, 1025, 0, 1, 1, 2048, 0, 1, 4326, 2054, 0, 1, 9102, ) return [ (33550, "d", 3, model_pixel_scale, False), (33922, "d", 6, model_tiepoint, False), (34735, "H", len(geo_key_directory), geo_key_directory, False), ] def write_rgba_geotiff(path, image, minx, maxy, pixel_width, pixel_height): tifffile.imwrite( path, image, photometric="rgb", extrasamples=["unassalpha"], metadata=None, extratags=geotiff_extratags(minx, maxy, pixel_width, pixel_height), ) def pixel_window_for_bounds(bounds, minx, maxy, pixel_width, pixel_height, width, height): geom_minx, geom_miny, geom_maxx, geom_maxy = bounds col_start = max(0, int(math.floor((geom_minx - minx) / pixel_width))) col_stop = min(width, int(math.ceil((geom_maxx - minx) / pixel_width))) row_start = max(0, int(math.floor((maxy - geom_maxy) / pixel_height))) row_stop = min(height, int(math.ceil((maxy - geom_miny) / pixel_height))) if row_start >= row_stop or col_start >= col_stop: return None return row_start, row_stop, col_start, col_stop def pixel_center_mask_for_geometry(geometry, window, minx, maxy, pixel_width, pixel_height): row_start, row_stop, col_start, col_stop = window x_coordinates = minx + (np.arange(col_start, col_stop, dtype=np.float64) + 0.5) * pixel_width y_coordinates = maxy - (np.arange(row_start, row_stop, dtype=np.float64) + 0.5) * pixel_height x_grid, y_grid = np.meshgrid(x_coordinates, y_coordinates) return np.asarray(shapely.contains_xy(geometry, x_grid, y_grid), dtype=bool) def pixel_center_mask_for_bounds(bounds, window, minx, maxy, pixel_width, pixel_height): """轴对齐矩形的像元中心判断。边界上的中心点不算在内,和多边形 contains 一致。""" row_start, row_stop, col_start, col_stop = window geom_minx, geom_miny, geom_maxx, geom_maxy = bounds cols = minx + (np.arange(col_start, col_stop, dtype=np.float64) + 0.5) * pixel_width rows = maxy - (np.arange(row_start, row_stop, dtype=np.float64) + 0.5) * pixel_height return ((rows > geom_miny) & (rows < geom_maxy))[:, None] & ((cols > geom_minx) & (cols < geom_maxx))[None, :] def pixel_window_from_point(x, y, minx, maxy, pixel_width, pixel_height, width, height): col = int((x - minx) / pixel_width) row = int((maxy - y) / pixel_height) if 0 <= row < height and 0 <= col < width: return row, row + 1, col, col + 1 return None def market_raster_layout(bounds, pixel_width, pixel_height, max_raster_pixels=None): minx, miny, maxx, maxy = bounds width = max(1, int(math.ceil((maxx - minx) / pixel_width))) height = max(1, int(math.ceil((maxy - miny) / pixel_height))) scale_factor = 1.0 pixel_limit = config.MAX_RASTER_PIXELS if max_raster_pixels is None else max_raster_pixels if pixel_limit and width * height > pixel_limit: scale_factor = math.sqrt((width * height) / pixel_limit) pixel_width *= scale_factor pixel_height *= scale_factor width = max(1, int(math.ceil((maxx - minx) / pixel_width))) height = max(1, int(math.ceil((maxy - miny) / pixel_height))) while width * height > pixel_limit: scale_factor *= 1.001 pixel_width *= 1.001 pixel_height *= 1.001 width = max(1, int(math.ceil((maxx - minx) / pixel_width))) height = max(1, int(math.ceil((maxy - miny) / pixel_height))) return minx, miny, maxx, maxy, pixel_width, pixel_height, width, height, scale_factor