File size: 9,995 Bytes
519ab98 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@Time : 2026/3/19 15:33
@File : image_precess.py
@Description :
"""
import os
from pathlib import Path
import cv2
import numpy as np
from matplotlib import pyplot as plt
def denoise_image(binary_image: np.ndarray) -> np.ndarray:
"""形态学开运算去噪"""
kernel = np.ones((2, 2), np.uint8)
return cv2.morphologyEx(binary_image, cv2.MORPH_OPEN, kernel)
def binarize_image(image: np.ndarray, method: str = 'adaptive') -> np.ndarray:
"""图像二值化"""
if len(image.shape) == 3:
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
else:
gray = image.copy()
if method == 'adaptive':
binary = cv2.adaptiveThreshold(
gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY_INV, 11, 2
)
elif method == 'otsu':
_, binary = cv2.threshold(
gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU
)
else:
_, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV)
return binary
def skeletonize_image(binary_image: np.ndarray) -> np.ndarray:
"""形态学骨架化 (迭代细化)"""
size = np.size(binary_image)
skel = np.zeros(binary_image.shape, np.uint8)
element = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3))
done = False
temp_img = binary_image.copy()
while not done:
eroded = cv2.erode(temp_img, element)
temp = cv2.dilate(eroded, element)
temp = cv2.subtract(temp_img, temp)
skel = cv2.bitwise_or(skel, temp)
temp_img = eroded.copy()
zeros = size - cv2.countNonZero(temp_img)
if zeros == size:
done = True
return skel
def preprocess_writer_image(
image: np.ndarray,
use_binarization: bool = True,
use_skeleton: bool = True
) -> np.ndarray:
"""
完整的图像预处理流程
Args:
image: 输入图像 (RGB 或灰度)
use_binarization: 是否二值化
use_skeleton: 是否骨架化
debug_path: 调试输出路径
Returns:
处理后的图像 (单通道或三通道)
"""
# 二值化
if use_binarization:
processed = binarize_image(image, method='otsu')
else:
processed = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) if len(image.shape) == 3 else image.copy()
# 去噪
processed = denoise_image(processed)
# 骨架化
if use_skeleton:
processed = skeletonize_image(processed)
return processed
def estimate_stroke_width_simple(binary_image, skeleton_image, k=1.5):
"""
【极简版】通过面积比估算平均笔画宽度
公式:Width ≈ Area_Binary / Area_Skeleton
"""
# 1. 统计前景像素数量 (面积)
# 假设输入是 0(背景) 和 255(前景)
binary_area = cv2.countNonZero(binary_image)
skeleton_area = cv2.countNonZero(skeleton_image)
# 2. 防止除以零
if skeleton_area == 0:
return 0.0
# 3. 计算宽度
avg_width = binary_area / skeleton_area * k
return avg_width
def estimate_stroke_width(image_orig, k=1.5):
"""
【极简版】通过面积比估算平均笔画宽度
公式:Width ≈ Area_Binary / Area_Skeleton
"""
binary = binarize_image(image_orig, method='otsu')
# B. 骨架化
skel = skeletonize_image(binary)
# C. 计算宽度
width = estimate_stroke_width_simple(binary, skel, k)
return width
def resize_image(image, target_size=100):
"""
预处理单张图片:保持长宽比 resize,边缘像素填充到目标大小
"""
if image is None:
raise ValueError("警告:无法读取图片")
h, w = image.shape[:2]
# 计算缩放比例(保持长宽比)
scale = min(target_size / h, target_size / w)
new_h = int(h * scale)
new_w = int(w * scale)
# Resize 图片
image_resized = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_AREA)
# 计算需要填充的像素量(居中填充)
pad_top = (target_size - new_h) // 2
pad_bottom = target_size - new_h - pad_top
pad_left = (target_size - new_w) // 2
pad_right = target_size - new_w - pad_left
# 使用255填充
image_padded = cv2.copyMakeBorder(
image_resized,
pad_top, pad_bottom, pad_left, pad_right,
borderType=cv2.BORDER_CONSTANT, value=(255, 255, 255),
)
return image_padded
def sta_polor():
# 配置路径
input_folder = "/path/to/circle_id/images/images/"
output_folder = "/path/to/circle_id/outputs/width_estimate2"
# 1. 创建输出目录
os.makedirs(output_folder, exist_ok=True)
print(f"✅ 输出目录已确认:{output_folder}")
# 2. 获取图片列表 (这里处理全部图片,如果想限制数量可以加 [:100])
# img_paths = list(Path(input_folder).glob("v2_*.png"))
all_paths = list(Path(input_folder).glob("*.png"))
img_paths = [p for p in all_paths if not p.name.startswith('v2_')]
# img_paths = img_paths[:100] # 调试时可取消注释
print(f"🔍 找到 {len(img_paths)} 张图片,开始处理...")
# --- 新增:用于统计的列表 ---
all_widths = []
valid_count = 0
invalid_count = 0
count = 0
for path in img_paths:
# 读取图片 (BGR)
image_orig = cv2.imread(str(path))
if image_orig is None:
print(f"⚠️ 无法读取图片:{path}")
continue
# --- 处理流程 ---
binary = binarize_image(image_orig, method='adaptive')
skel = skeletonize_image(binary)
width = estimate_stroke_width_simple(binary, skel)
# --- 数据收集 ---
if width > 0:
all_widths.append(width)
valid_count += 1
else:
invalid_count += 1
# print(f"⚠️ 无效宽度 (骨架为空): {path.name}")
# --- 可视化准备 (保持原有逻辑) ---
h, w = image_orig.shape[:2]
image_display = image_orig.copy()
text = f"W: {width:.2f}"
font = cv2.FONT_HERSHEY_SIMPLEX
font_scale = 0.6
thickness = 2
# cv2.putText(image_display, text, (5, 45), font, font_scale, (0, 255, 0), thickness)
# cv2.putText(image_display, "Original", (15, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)
#
# binary_bgr = cv2.cvtColor(binary, cv2.COLOR_GRAY2BGR)
# cv2.putText(binary_bgr, "Binary", (15, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)
#
# skel_bgr = cv2.cvtColor(skel, cv2.COLOR_GRAY2BGR)
# cv2.putText(skel_bgr, "Skeleton", (15, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)
#
# combined_image = np.hstack([image_display, binary_bgr, skel_bgr])
#
# # --- 保存结果 ---
# output_path = os.path.join(output_folder, path.name)
# cv2.imwrite(output_path, combined_image)
count += 1
if count % 50 == 0:
print(f"已处理 {count}/{len(img_paths)} 张...")
print(f"\n🎉 图片处理完成!共处理 {count} 张,有效样本 {valid_count} 张,无效 {invalid_count} 张。")
# ================= 统计与绘图 =================
if len(all_widths) > 0:
# 1. 计算统计指标
widths_arr = np.array(all_widths)
mean_w = np.mean(widths_arr)
median_w = np.median(widths_arr)
std_w = np.std(widths_arr)
min_w = np.min(widths_arr)
max_w = np.max(widths_arr)
print("\n📊 笔画宽度统计报告:")
print(f" 平均宽度 (Mean): {mean_w:.2f} px")
print(f" 中位数 (Median): {median_w:.2f} px")
print(f" 标准差 (Std): {std_w:.2f} px")
print(f" 最小值 (Min): {min_w:.2f} px")
print(f" 最大值 (Max): {max_w:.2f} px")
# 2. 绘制直方图
plt.style.use('seaborn-v0_8-whitegrid') # 使用好看的风格
fig, ax = plt.subplots(figsize=(10, 6))
# 绘制直方图
n, bins, patches = ax.hist(all_widths, bins=50, color='#4CAF50', alpha=0.7, edgecolor='black', linewidth=0.5)
# 添加统计线
ax.axvline(mean_w, color='red', linestyle='dashed', linewidth=2, label=f'Mean: {mean_w:.2f}')
ax.axvline(median_w, color='blue', linestyle='solid', linewidth=2, label=f'Median: {median_w:.2f}')
# 添加标题和标签
ax.set_title(f'Stroke Width Distribution (N={valid_count})', fontsize=14, fontweight='bold')
ax.set_xlabel('Stroke Width (pixels)', fontsize=12)
ax.set_ylabel('Frequency (Count)', fontsize=12)
ax.legend()
# 添加文本框显示详细统计
textstr = f'Mean: {mean_w:.2f}\nMedian: {median_w:.2f}\nStd: {std_w:.2f}\nMin: {min_w:.2f}\nMax: {max_w:.2f}'
props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)
ax.text(0.95, 0.95, textstr, transform=ax.transAxes, fontsize=10,
verticalalignment='top', horizontalalignment='right', bbox=props)
# 保存图表
hist_plot_path = os.path.join(output_folder, "stroke_width_distribution_train.png")
plt.savefig(hist_plot_path, dpi=150, bbox_inches='tight')
print(f"\n📈 直方图已保存至:{hist_plot_path}")
# 如果在本地有图形界面,可以显示;服务器后台运行则不会弹窗
# plt.show()
plt.close()
else:
print("\n⚠️ 没有有效的宽度数据,无法绘制直方图。请检查二值化或骨架化逻辑。")
print(f"\n💡 提示:所有结果已保存至 {output_folder}")
# ================= 使用示例 =================
if __name__ == "__main__":
path = "/path/to/circle_id/images/images/39890.png"
img = cv2.imread(path)
img_new = resize_image(img)
write_path = "/path/to/circle_id/outputs/augment2/" + path.split("/")[-1]
cv2.imwrite(write_path, img_new)
|