import numpy as np
import pya
import cv2
import os
import matplotlib.pyplot as plt
import json
import traceback
import math
def create_flower_gds_with_rotated_rectangles(image_path, output_gds="flower_rotated_rectangles.gds"):
"""
根据花朵图像的不同区域生成带旋转矩形的GDS
每个图层都有可旋转的长方形
"""
print("=" * 70)
print("花朵区域化旋转矩形GDS生成器 (精确周期)")
print("=" * 70)
# 1. 读取和处理图像
if not os.path.exists(image_path):
print(f"错误: 文件 {image_path} 不存在")
return None, None, None
# 读取灰度图像
img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
if img is None:
print("无法读取图像")
return None, None, None
print(f"图像尺寸: {img.shape}")
print(f"灰度值范围: {img.min()} - {img.max()}")
# 2. 将图像放大10倍
print(f"\n将图像放大10倍...")
original_height, original_width = img.shape
# 使用最近邻插值放大图像(保持边缘锐利)
new_width = original_width * 10
new_height = original_height * 10
# 放大图像
img_large = cv2.resize(img, (new_width, new_height),
interpolation=cv2.INTER_NEAREST)
print(f"放大后图像尺寸: {img_large.shape}")
print(f"放大倍数: 10倍 (像素: {original_width}×{original_height} → {new_width}×{new_height})")
# 保存放大后的图像
cv2.imwrite("enlarged_10x.png", img_large)
print(f"✓ 放大后的图像已保存: enlarged_10x.png")
# 使用放大后的图像
img = img_large
# 3. 分析图像灰度值分布
unique_vals, counts = np.unique(img, return_counts=True)
print(f"\n灰度值分布 (前10个):")
for i, (val, count) in enumerate(zip(unique_vals[:10], counts[:10])):
if count > 0:
print(f" 灰度值 {val:3d}: {count:8d} 像素 ({count / img.size * 100:.1f}%)")
# 4. 定义不同区域的配置 - 添加旋转角度
# 每个图层有不同的旋转角度配置
region_configs = {
'dark_petals': {
'gray_range': (51, 53), # 深灰色区域
'layer': 1, # 第1层
'datatype': 0,
'description': '深灰色花瓣 - 0度旋转',
'color': (255, 0, 0), # 红色
'rect_config': {
'rect1': {'length': 0.3, 'width': 0.2, 'rotation': 0}, # 长方形1: 0.3×0.2, 旋转0度
'rect2': {'length': 0.2, 'width': 0.3, 'rotation': 0}, # 长方形2: 0.2×0.3, 旋转0度
'period_x': 0.74, # X方向周期
'period_y': 0.4, # Y方向周期
'rect_type': 'dual_rect'
}
},
'medium_petals': {
'gray_range': (80, 82), # 中等灰色区域
'layer': 2, # 第2层
'datatype': 0,
'description': '中等灰色花瓣 - 0度旋转',
'color': (255, 128, 0), # 橙色
'rect_config': {
'rect1': {'length': 0.28, 'width': 0.2, 'rotation': 0},
'rect2': {'length': 0.2, 'width': 0.28, 'rotation': 0},
'period_x': 0.8, # 修改为0.74
'period_y': 0.4,
'rect_type': 'dual_rect'
}
},
'light_petals': {
'gray_range': (101, 103), # 浅灰色区域
'layer': 3, # 第3层
'datatype': 0,
'description': '浅灰色花瓣 - 45度旋转',
'color': (255, 255, 0), # 黄色
'rect_config': {
'rect1': {'length': 0.3, 'width': 0.15, 'rotation': 45},
'rect2': {'length': 0.15, 'width': 0.3, 'rotation': 45},
'period_x': 0.8, # 修改为0.74
'period_y': 0.4,
'rect_type': 'dual_rect'
}
},
'center': {
'gray_range': (126, 128), # 花蕊区域
'layer': 4, # 第4层
'datatype': 0,
'description': '花蕊中心 - 0度/90度',
'color': (0, 255, 0), # 绿色
'rect_config': {
'rect1': {'length': 0.3, 'width': 0.2, 'rotation': 45}, # 水平
'rect2': {'length': 0.2, 'width': 0.3, 'rotation': 45}, # 垂直
'period_x': 0.74, # 修改为0.74
'period_y': 0.4,
'rect_type': 'dual_rect'
}
},
'stem': {
'gray_range': (153, 155), # 茎
'layer': 5, # 第5层
'datatype': 0,
'description': '花茎 - 15度/105度',
'color': (0, 128, 255), # 浅蓝色
'rect_config': {
'rect1': {'length': 0.3, 'width': 0.2, 'rotation': 22},
'rect2': {'length': 0.2, 'width': 0.3, 'rotation': 22},
'period_x': 0.74, # 修改为0.74
'period_y': 0.4,
'rect_type': 'dual_rect'
}
},
'leaves': {
'gray_range': (178, 180), # 叶子
'layer': 6, # 第6层
'datatype': 0,
'description': '叶子1 - 75度旋转',
'color': (128, 0, 255), # 紫色
'rect_config': {
'rect1': {'length': 0.3, 'width': 0.2, 'rotation': 22},
'rect2': {'length': 0.2, 'width': 0.3, 'rotation': 22},
'period_x': 0.76, # 修改为0.74
'period_y': 0.4,
'rect_type': 'dual_rect'
}
},
'leaves1': {
'gray_range': (202, 204), # 叶子
'layer': 7, # 第7层
'datatype': 0,
'description': '叶子2 - 20度/110度',
'color': (255, 0, 255), # 粉色
'rect_config': {
'rect1': {'length': 0.3, 'width': 0.18, 'rotation': 67},
'rect2': {'length': 0.18, 'width': 0.3, 'rotation': 67},
'period_x': 0.74, # 修改为0.74
'period_y': 0.4,
'rect_type': 'dual_rect'
}
},
'leaves2': {
'gray_range': (228, 230), # 叶子
'layer': 8, # 第8层
'datatype': 0,
'description': '叶子3 - 10度/100度',
'color': (0, 255, 255), # 青色
'rect_config': {
'rect1': {'length': 0.3, 'width': 0.18, 'rotation': 67},
'rect2': {'length': 0.18, 'width': 0.3, 'rotation': 67},
'period_x': 0.76, # 修改为0.74
'period_y': 0.4,
'rect_type': 'dual_rect'
}
}
}
# 5. 创建GDS布局
layout = pya.Layout()
layout.dbu = 0.001 # 1nm per database unit
top_cell = layout.create_cell("FLOWER_ROTATED_RECTANGLES")
# 创建所有图层
layer_indices = {}
for region_name, config in region_configs.items():
layer_key = (config['layer'], config['datatype'])
if layer_key not in layer_indices:
layer_indices[layer_key] = layout.layer(config['layer'], config['datatype'])
print(f"创建图层: 图层{config['layer']} (数据类型{config['datatype']})")
print(f"总共创建了 {len(layer_indices)} 个图层")
# 6. 为每个区域生成带旋转的矩形阵列
height, width = img.shape
# 使用浮点数步长实现精确周期
scale_factor = 0.1 # 像素转微米的缩放因子
print(f"\n缩放因子: {scale_factor} µm/像素")
print(f"开始生成带旋转的矩形阵列 (精确周期)...")
region_stats = {}
total_rectangles = 0
for region_name, config in region_configs.items():
print(f"\n处理区域: {config['description']}")
# 创建该区域的掩码
min_gray, max_gray = config['gray_range']
mask = (img >= min_gray) & (img <= max_gray)
# 统计区域大小
region_pixels = np.sum(mask)
region_stats[region_name] = region_pixels
if region_pixels == 0:
print(f" ⚠️ 未找到像素,跳过")
continue
print(f" 找到像素: {region_pixels} 个")
print(f" 灰度范围: {min_gray}-{max_gray}")
# 获取图层索引
layer_index = layer_indices[(config['layer'], config['datatype'])]
# 获取矩形配置
rect_config = config['rect_config']
rect1_length = rect_config['rect1']['length']
rect1_width = rect_config['rect1']['width']
rect1_rotation = rect_config['rect1']['rotation']
rect2_length = rect_config['rect2']['length']
rect2_width = rect_config['rect2']['width']
rect2_rotation = rect_config['rect2']['rotation']
period_x = rect_config['period_x']
period_y = rect_config['period_y']
print(f" 旋转矩形结构:")
print(f" 长方形1: {rect1_length}×{rect1_width} µm, 旋转角度: {rect1_rotation}度")
print(f" 长方形2: {rect2_length}×{rect2_width} µm, 旋转角度: {rect2_rotation}度")
print(f" 精确周期: {period_x}×{period_y} µm")
rect_count = 0
# 使用浮点数步长实现精确周期
step_x_float = period_x / scale_factor # 0.74 / 0.1 = 7.4像素
step_y_float = period_y / scale_factor # 0.4 / 0.1 = 4.0像素
print(f" 浮点步长: {step_x_float:.2f} × {step_y_float:.2f} 像素")
# 使用浮点数循环实现精确周期
y_float = 0.0
while y_float < height:
x_float = 0.0
while x_float < width:
# 将浮点坐标四舍五入到最近的整数索引
x_idx = int(round(x_float))
y_idx = int(round(y_float))
# 检查索引是否在范围内
if 0 <= x_idx < width and 0 <= y_idx < height and mask[y_idx, x_idx]:
# 使用浮点数坐标计算中心位置,确保精确
center_x = x_float * scale_factor
center_y = (height - y_float) * scale_factor # 翻转Y轴
# 生成第一个旋转矩形
rect1_vertices = self_rotated_rectangle(
center_x, center_y,
rect1_length / 2.0, rect1_width / 2.0,
rect1_rotation
)
# 创建多边形并添加到图层
poly1 = pya.DPolygon(rect1_vertices)
top_cell.shapes(layer_index).insert(poly1)
rect_count += 1
# 生成第二个旋转矩形,位置偏移半个周期
offset_x = period_x / 2.0
rect2_vertices = self_rotated_rectangle(
center_x + offset_x, center_y,
rect2_length / 2.0, rect2_width / 2.0,
rect2_rotation
)
poly2 = pya.DPolygon(rect2_vertices)
top_cell.shapes(layer_index).insert(poly2)
rect_count += 1
x_float += step_x_float
y_float += step_y_float
print(f" 生成旋转矩形: {rect_count} 个 (2个/单元)")
print(f" 图层: {config['layer']}")
total_rectangles += rect_count
# 7. 保存GDS文件
print(f"\n保存GDS文件: {output_gds}")
layout.write(output_gds)
# 获取布局边界信息
bbox = top_cell.bbox()
print(f"GDS布局边界: {bbox.left:.1f}, {bbox.bottom:.1f} → {bbox.right:.1f}, {bbox.top:.1f} um")
print(f"布局尺寸: {bbox.width():.1f} × {bbox.height():.1f} um")
print(f"总矩形数: {total_rectangles}")
# 8. 生成预览和统计
generate_previews(img, region_configs, region_stats, scale_factor)
# 9. 保存配置信息
save_configuration(region_configs, output_gds, total_rectangles, bbox)
return region_configs, region_stats, total_rectangles
def self_rotated_rectangle(center_x, center_y, half_length, half_width, rotation_deg):
"""
创建绕中心旋转的长方形顶点
参数:
center_x, center_y: 中心坐标
half_length: 半长
half_width: 半宽
rotation_deg: 旋转角度(度)
返回:
4个顶点坐标的列表
"""
# 将角度转换为弧度
rotation_rad = math.radians(rotation_deg)
# 未旋转前的四个角点(相对于中心)
corners_rel = [
(-half_width, -half_length), # 左下
(half_width, -half_length), # 右下
(half_width, half_length), # 右上
(-half_width, half_length) # 左上
]
# 旋转矩阵
cos_theta = math.cos(rotation_rad)
sin_theta = math.sin(rotation_rad)
# 计算旋转后的顶点
vertices = []
for dx, dy in corners_rel:
# 应用旋转
x_rot = dx * cos_theta - dy * sin_theta
y_rot = dx * sin_theta + dy * cos_theta
# 平移回中心位置
x = center_x + x_rot
y = center_y + y_rot
vertices.append(pya.DPoint(x, y))
return vertices
def generate_previews(img, configs, stats, scale_factor):
"""生成预览图像"""
fig = plt.figure(figsize=(20, 12))
# 子图1: 原始灰度图像
ax1 = plt.subplot(2, 4, 1)
ax1.imshow(img, cmap='gray', vmin=0, vmax=255)
ax1.set_title("原始花朵图像", fontsize=12, fontweight='bold')
ax1.set_xlabel(f"宽度: {img.shape[1]} 像素")
ax1.set_ylabel(f"高度: {img.shape[0]} 像素")
im1 = ax1.imshow(img, cmap='gray', vmin=0, vmax=255)
plt.colorbar(im1, ax=ax1, label='灰度值')
# 子图2: 旋转矩形结构示意图
ax2 = plt.subplot(2, 4, 2)
ax2.axis('off')
# 获取一个示例配置
sample_config = None
for region_name, config in configs.items():
if 'rect_config' in config:
sample_config = config
break
if sample_config:
rect_config = sample_config['rect_config']
unit_cell_info = "旋转矩形结构示意图\n"
unit_cell_info += "=" * 20 + "\n\n"
unit_cell_info += f"精确周期: {rect_config['period_x']}×{rect_config['period_y']}µm\n\n"
unit_cell_info += f"长方形1:\n"
unit_cell_info += f" 尺寸: {rect_config['rect1']['length']}×{rect_config['rect1']['width']}µm\n"
unit_cell_info += f" 旋转: {rect_config['rect1']['rotation']}度\n\n"
unit_cell_info += f"长方形2:\n"
unit_cell_info += f" 尺寸: {rect_config['rect2']['length']}×{rect_config['rect2']['width']}µm\n"
unit_cell_info += f" 旋转: {rect_config['rect2']['rotation']}度"
ax2.text(0.1, 0.5, unit_cell_info, fontsize=10,
verticalalignment='center', linespacing=1.5,
transform=ax2.transAxes)
# 绘制示意图
ax2_sub = ax2.inset_axes([0.6, 0.2, 0.3, 0.6])
ax2_sub.set_aspect('equal')
ax2_sub.set_xlim(0, 1)
ax2_sub.set_ylim(0, 1)
ax2_sub.set_xticks([])
ax2_sub.set_yticks([])
# 绘制旋转矩形示意图
angle1 = rect_config['rect1']['rotation']
angle2 = rect_config['rect2']['rotation']
# 使用matplotlib的旋转矩形
from matplotlib.patches import Rectangle
rect1 = Rectangle((0.2, 0.3), 0.3, 0.2, angle=angle1,
facecolor='red', alpha=0.7,
label=f"{angle1}°")
rect2 = Rectangle((0.5, 0.5), 0.2, 0.3, angle=angle2,
facecolor='blue', alpha=0.7,
label=f"{angle2}°")
ax2_sub.add_patch(rect1)
ax2_sub.add_patch(rect2)
# 绘制周期框
period_box = Rectangle((0, 0), 0.8, 0.4, fill=False,
edgecolor='black', linestyle='--', linewidth=1)
ax2_sub.add_patch(period_box)
ax2_sub.annotate('', xy=(0.8, 0.2), xytext=(0, 0.2),
arrowprops=dict(arrowstyle='<->', color='green'))
ax2_sub.text(0.4, 0.15, f"{rect_config['period_x']}µm", ha='center', fontsize=8)
ax2_sub.annotate('', xy=(0.4, 0), xytext=(0.4, 0.4),
arrowprops=dict(arrowstyle='<->', color='green'))
ax2_sub.text(0.45, 0.2, f"{rect_config['period_y']}µm", ha='center', fontsize=8)
ax2_sub.legend(loc='upper right', fontsize=7)
# 子图3: 区域划分彩色图
ax3 = plt.subplot(2, 4, 3)
# 创建彩色区域图
color_img = np.zeros((*img.shape, 3), dtype=np.uint8)
# 为每个有效区域上色
for region_name, config in configs.items():
if stats.get(region_name, 0) > 0:
min_gray, max_gray = config['gray_range']
mask = (img >= min_gray) & (img <= max_gray)
color_img[mask] = config['color']
ax3.imshow(color_img)
ax3.set_title("8图层区域划分", fontsize=12, fontweight='bold')
ax3.set_xlabel("不同颜色=不同图层")
ax3.set_ylabel(f"共{len([s for s in stats.values() if s > 0])}个有效区域")
# 创建图例
from matplotlib.patches import Patch
legend_elements = []
for region_name, config in configs.items():
count = stats.get(region_name, 0)
if count > 0:
legend_text = f"图层{config['layer']}:\n"
legend_text += f"{config['description'][:8]}\n"
if 'rect_config' in config:
angle1 = config['rect_config']['rect1']['rotation']
angle2 = config['rect_config']['rect2']['rotation']
legend_text += f"旋转: {angle1}/{angle2}°\n"
legend_text += f"像素:{count}"
legend_elements.append(
Patch(facecolor=np.array(config['color']) / 255,
label=legend_text, edgecolor='black'))
if legend_elements:
ax3.legend(handles=legend_elements, loc='upper left',
bbox_to_anchor=(1.05, 1), fontsize=7, framealpha=0.9, title="图层说明")
# 子图4: 图层分布柱状图
ax4 = plt.subplot(2, 4, 4)
layers = []
pixel_counts = []
colors = []
for region_name, config in configs.items():
count = stats.get(region_name, 0)
if count > 0:
layers.append(f"L{config['layer']}")
pixel_counts.append(count)
colors.append(np.array(config['color']) / 255)
if pixel_counts:
bars = ax4.bar(range(len(layers)), pixel_counts, color=colors, edgecolor='black')
ax4.set_xlabel('图层')
ax4.set_ylabel('像素数量')
ax4.set_title('各图层像素数量', fontsize=12, fontweight='bold')
ax4.set_xticks(range(len(layers)))
ax4.set_xticklabels(layers, fontsize=10)
# 添加数值标签
for bar in bars:
height = bar.get_height()
ax4.text(bar.get_x() + bar.get_width() / 2, height,
f'{int(height):,}', ha='center', va='bottom', fontsize=8)
ax4.grid(True, alpha=0.3, axis='y')
# 子图5: 灰度值分布直方图
ax5 = plt.subplot(2, 4, 5)
# 计算灰度直方图
hist, bins = np.histogram(img.flatten(), bins=256, range=[0, 256])
ax5.bar(bins[:-1], hist, width=1, color='gray', alpha=0.7)
ax5.set_xlabel('灰度值')
ax5.set_ylabel('像素数量')
ax5.set_title('灰度值分布直方图', fontsize=12, fontweight='bold')
ax5.set_xlim(0, 256)
ax5.grid(True, alpha=0.3)
# 标记配置的灰度范围
for region_name, config in configs.items():
if stats.get(region_name, 0) > 0:
min_gray, max_gray = config['gray_range']
color = np.array(config['color']) / 255
ax5.axvspan(min_gray, max_gray, alpha=0.3, color=color)
ax5.text((min_gray + max_gray) / 2, ax5.get_ylim()[1] * 0.9,
f"L{config['layer']}", ha='center', fontsize=8, color=color)
# 子图6: 旋转角度对比图
ax6 = plt.subplot(2, 4, 6)
layers_angle = []
angles1 = []
angles2 = []
colors_angle = []
for region_name, config in configs.items():
if stats.get(region_name, 0) > 0 and 'rect_config' in config:
layers_angle.append(f"L{config['layer']}")
angles1.append(config['rect_config']['rect1']['rotation'])
angles2.append(config['rect_config']['rect2']['rotation'])
colors_angle.append(np.array(config['color']) / 255)
if layers_angle:
x = np.arange(len(layers_angle))
width = 0.35
bars1 = ax6.bar(x - width / 2, angles1, width,
label='长方形1角度', color=colors_angle, edgecolor='black')
bars2 = ax6.bar(x + width / 2, angles2, width,
label='长方形2角度', color=[c * 0.7 for c in colors_angle], edgecolor='black')
ax6.set_xlabel('图层')
ax6.set_ylabel('旋转角度 (度)')
ax6.set_title('各图层旋转角度', fontsize=12, fontweight='bold')
ax6.set_xticks(x)
ax6.set_xticklabels(layers_angle, fontsize=10)
ax6.legend(fontsize=9)
ax6.grid(True, alpha=0.3, axis='y')
# 添加数值标签
for i, (bar1, bar2) in enumerate(zip(bars1, bars2)):
ax6.text(bar1.get_x() + bar1.get_width() / 2, bar1.get_height(),
f'{angles1[i]}°', ha='center', va='bottom', fontsize=8)
ax6.text(bar2.get_x() + bar2.get_width() / 2, bar2.get_height(),
f'{angles2[i]}°', ha='center', va='bottom', fontsize=8)
# 子图7: 周期配置详情
ax7 = plt.subplot(2, 4, 7)
ax7.axis('off')
config_text = "🔧 各图层精确周期配置\n"
config_text += "=" * 20 + "\n\n"
for region_name, config in configs.items():
count = stats.get(region_name, 0)
if count > 0 and 'rect_config' in config:
config_text += f"图层{config['layer']}:\n"
config_text += f" {config['description']}\n"
rect_config = config['rect_config']
config_text += f" 矩形1: {rect_config['rect1']['length']}×{rect_config['rect1']['width']} µm\n"
config_text += f" 旋转: {rect_config['rect1']['rotation']}度\n"
config_text += f" 矩形2: {rect_config['rect2']['length']}×{rect_config['rect2']['width']} µm\n"
config_text += f" 旋转: {rect_config['rect2']['rotation']}度\n"
config_text += f" 精确周期: {rect_config['period_x']}×{rect_config['period_y']} µm\n"
# 计算步长
step_x = rect_config['period_x'] / 0.1
step_y = rect_config['period_y'] / 0.1
config_text += f" 浮点步长: {step_x:.2f}×{step_y:.2f} 像素\n\n"
ax7.text(0.05, 0.5, config_text, fontsize=8,
verticalalignment='center', linespacing=1.3,
transform=ax7.transAxes)
# 子图8: 信息汇总
ax8 = plt.subplot(2, 4, 8)
ax8.axis('off')
total_pixels = img.size
active_pixels = sum(stats.values())
active_regions = len([s for s in stats.values() if s > 0])
info_text = "📊 8图层旋转矩形GDS\n"
info_text += "=" * 30 + "\n\n"
info_text += f"图像尺寸: {img.shape[1]} × {img.shape[0]} 像素\n"
info_text += f"总像素数: {total_pixels:,}\n"
info_text += f"有效区域: {active_regions}/8 个\n"
info_text += f"有效像素: {active_pixels:,} ({active_pixels / total_pixels * 100:.1f}%)\n"
info_text += f"缩放因子: {scale_factor} µm/像素\n"
info_text += f"GDS单位: 0.001 (1nm)\n"
info_text += f"周期模式: 精确0.74×0.4 µm\n\n"
info_text += "🎯 主要特性:\n"
info_text += "• 所有图层使用旋转矩形\n"
info_text += "• 每个单元: 2个不同角度矩形\n"
info_text += "• 精确周期: 0.74×0.4 µm\n"
info_text += "• 浮点步长: 确保周期精确\n"
ax8.text(0.05, 0.5, info_text, fontsize=9,
verticalalignment='center', linespacing=1.3,
transform=ax8.transAxes)
plt.suptitle("花朵GDS生成分析 (8图层旋转矩形结构, 精确周期)", fontsize=16, fontweight='bold', y=0.98)
plt.tight_layout()
# 保存预览图像
plt.savefig("flower_rotated_gds_preview.png", dpi=150, bbox_inches='tight')
print("✓ 预览图像已保存: flower_rotated_gds_preview.png")
plt.show()
def save_configuration(configs, gds_filename, total_rects, bbox):
"""保存配置到JSON文件"""
config_data = {}
for region_name, config in configs.items():
config_data[region_name] = {
'description': config['description'],
'gray_range': config['gray_range'],
'layer': config['layer'],
'datatype': config['datatype'],
'color': config['color']
}
if 'rect_config' in config:
config_data[region_name]['rect_config'] = config['rect_config']
config_filename = gds_filename.replace('.gds', '_config.json')
with open(config_filename, 'w', encoding='utf-8') as f:
json.dump(config_data, f, indent=2, ensure_ascii=False)
print(f"✓ 配置已保存: {config_filename}")
# 生成简化的配置说明
guide_filename = gds_filename.replace('.gds', '_guide.txt')
with open(guide_filename, 'w', encoding='utf-8') as f:
f.write("花朵8图层旋转矩形GDS配置说明 (精确周期)\n")
f.write("=" * 60 + "\n\n")
f.write("📁 文件信息:\n")
f.write(f"GDS文件: {gds_filename}\n")
f.write(f"生成时间: {np.datetime64('now')}\n")
f.write(f"总矩形数: {total_rects:,}\n")
f.write(f"布局边界: {bbox.left:.1f}, {bbox.bottom:.1f} → {bbox.right:.1f}, {bbox.top:.1f} µm\n")
f.write(f"布局尺寸: {bbox.width():.1f} × {bbox.height():.1f} µm\n\n")
f.write("🎨 8图层旋转矩形配置 (精确周期0.74×0.4µm):\n")
f.write("=" * 30 + "\n")
for region_name, config in configs.items():
f.write(f"\n图层 {config['layer']}: {config['description']}\n")
f.write(f" 灰度范围: {config['gray_range'][0]}-{config['gray_range'][1]}\n")
if 'rect_config' in config:
rect_config = config['rect_config']
f.write(f" 结构类型: 旋转双矩形单元\n")
f.write(f" 长方形1: {rect_config['rect1']['length']}×{rect_config['rect1']['width']} µm\n")
f.write(f" 旋转角度: {rect_config['rect1']['rotation']}度\n")
f.write(f" 长方形2: {rect_config['rect2']['length']}×{rect_config['rect2']['width']} µm\n")
f.write(f" 旋转角度: {rect_config['rect2']['rotation']}度\n")
f.write(f" 精确周期: {rect_config['period_x']}×{rect_config['period_y']} µm\n")
# 计算步长
step_x = rect_config['period_x'] / 0.1
step_y = rect_config['period_y'] / 0.1
f.write(f" 浮点步长: {step_x:.2f}×{step_y:.2f} 像素\n")
# 计算角度差
angle_diff = abs(rect_config['rect2']['rotation'] - rect_config['rect1']['rotation'])
f.write(f" 角度差: {angle_diff}度\n")
f.write(f" 数据类型: {config['datatype']}\n")
f.write(f" 颜色: RGB{config['color']}\n")
f.write("\n" + "=" * 60 + "\n")
f.write("\n精确周期实现方法:\n")
f.write("1. 使用浮点数步长: 7.4×4.0 像素\n")
f.write("2. 浮点坐标遍历: 确保0.74µm周期精确\n")
f.write("3. 四舍五入到最近像素: 保持图像匹配\n")
f.write("4. 缩放因子: 0.1 µm/像素\n\n")
f.write("使用说明:\n")
f.write("1. 用KLayout打开GDS文件查看\n")
f.write("2. 在KLayout中按 'F' 键打开图层面板\n")
f.write("3. 可以独立控制每个图层的显示/隐藏\n")
f.write("4. 所有图层都使用旋转矩形结构\n")
f.write("5. 旋转是绕矩形中心进行的\n")
print(f"✓ 使用指南已保存: {guide_filename}")
def main():
print("🌸 花朵8图层旋转矩形GDS生成器 (精确周期) 🌸")
print("\n旋转矩形配置说明:")
print(" • 所有图层: 使用旋转双矩形结构")
print(" • 每个单元: 2个不同角度的矩形")
print(" • 旋转中心: 矩形几何中心")
print(" • 角度范围: 0-360度任意角度")
print(" • 精确周期: 0.74×0.4 µm (浮点步长实现)")
print(" • 步长: 7.4×4.0 像素 (浮点数)")
# 查找图像文件
possible_files = [
"flower.png", "flower.jpg", "flower.jpeg",
"image.png", "image.jpg", "drawing.png",
"input.png", "flower.bmp", "黑白花.png"
]
image_file = None
for file in possible_files:
if os.path.exists(file):
image_file = file
break
if image_file is None:
print("\n⚠️ 未找到花朵图像文件")
print("请将花朵图片文件放在当前目录")
print("当前目录文件:", os.listdir('.'))
image_file = input("\n请输入图像文件名: ").strip()
if not os.path.exists(image_file):
print(f"错误: 文件 {image_file} 不存在")
return
print(f"\n找到图像文件: {image_file}")
# 生成GDS
try:
configs, stats, total_rects = create_flower_gds_with_rotated_rectangles(
image_path=image_file,
output_gds="flower_8layer_rotated_rect_074.gds"
)
if configs is None:
print("GDS生成失败")
return
# 总结
print("\n" + "=" * 70)
print("🎉 8图层旋转矩形GDS生成完成! 🎉")
print("=" * 70)
active_regions = len([s for s in stats.values() if s > 0])
active_pixels = sum(stats.values())
print(f"\n📊 生成统计:")
print(f" 有效区域: {active_regions}/8 个")
print(f" 有效像素: {active_pixels:,} 个")
print(f" 总矩形数: {total_rects:,} 个")
print(f"\n📁 生成的文件:")
print(f" 1. flower_8layer_rotated_rect_074.gds - 主GDS文件")
print(f" 2. flower_8layer_rotated_rect_074_config.json - 配置文件")
print(f" 3. flower_8layer_rotated_rect_074_guide.txt - 使用说明")
print(f" 4. flower_rotated_gds_preview.png - 预览图像")
# 显示各图层配置详情
print(f"\n📏 各图层精确周期配置:")
for region_name, config in configs.items():
if stats.get(region_name, 0) > 0 and 'rect_config' in config:
rect_config = config['rect_config']
print(f"\n 图层{config['layer']}: {config['description']}")
print(
f" 长方形1: {rect_config['rect1']['length']}×{rect_config['rect1']['width']} µm, {rect_config['rect1']['rotation']}度")
print(
f" 长方形2: {rect_config['rect2']['length']}×{rect_config['rect2']['width']} µm, {rect_config['rect2']['rotation']}度")
print(f" 精确周期: {rect_config['period_x']}×{rect_config['period_y']} µm")
print(f" 浮点步长: {rect_config['period_x'] / 0.1:.2f}×{rect_config['period_y'] / 0.1:.2f} 像素")
print(f"\n🎯 下一步:")
print(f" 1. 用KLayout查看: klayout flower_8layer_rotated_rect_074.gds")
print(f" 2. 放大查看旋转矩形的角度")
print(f" 3. 验证周期是否精确为0.74µm")
print(f" 4. 在KLayout中,可以独立控制每个图层的显示")
print(f" 5. 查看预览图像: flower_rotated_gds_preview.png")
except Exception as e:
print(f"\n❌ 生成过程中出错: {e}")
traceback.print_exc()
if __name__ == "__main__":
# 检查所需库
try:
import cv2
import pya
import numpy as np
import matplotlib.pyplot as plt
import math
except ImportError as e:
print(f"❌ 缺少所需库: {e}")
print("请安装以下库:")
print("pip install opencv-python numpy matplotlib")
print("KLayout Python API 需要单独安装")
exit(1)
main()
结果:

243




被折叠的 条评论
为什么被折叠?



