from pathlib import Path
import cv2, numpy as np, csv, json
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib import font_manager

out=Path(__file__).resolve().parent/'aruco_preparation_v2'; out.mkdir(exist_ok=True)
dictionary=cv2.aruco.getPredefinedDictionary(cv2.aruco.DICT_4X4_50)
detector=cv2.aruco.ArucoDetector(dictionary,cv2.aruco.DetectorParameters())
marker=cv2.aruco.generateImageMarker(dictionary,0,360)
canvas=np.full((600,800),255,np.uint8); canvas[120:480,220:580]=marker
cv2.imwrite(str(out/'marker_id0.png'),cv2.copyMakeBorder(marker,60,60,60,60,cv2.BORDER_CONSTANT,value=255))
# Gray rectangle applied to the rightmost fraction of the marker; 0% is the unoccluded control.
results=[]
for percent in (0,5,10,15,20,25,30,40,50):
 image=canvas.copy(); width=round(360*percent/100)
 if width: image[120:480,580-width:580]=160
 corners,ids,_=detector.detectMarkers(image)
 ids_list=[] if ids is None else [int(x) for x in ids.ravel()]
 found=0 in ids_list
 err=''
 annotated=cv2.cvtColor(image,cv2.COLOR_GRAY2BGR)
 if found:
  cv2.aruco.drawDetectedMarkers(annotated,corners,ids)
  c=corners[ids_list.index(0)].reshape(4,2); center=c.mean(axis=0)
  err=float(np.linalg.norm(center-[399.5,299.5]))
 cv2.imwrite(str(out/f'occlusion_{percent:02}.png'),annotated)
 results.append({'occlusion_percent':percent,'detected':int(found),'center_error_px':err})
with (out/'synthetic_results.csv').open('w',encoding='utf-8',newline='') as f:
 w=csv.DictWriter(f,fieldnames=results[0].keys());w.writeheader();w.writerows(results)
font='C:/Windows/Fonts/msyh.ttc'; font_manager.fontManager.addfont(font);plt.rcParams['font.family']=font_manager.FontProperties(fname=font).get_name();plt.rcParams['axes.unicode_minus']=False
fig,axs=plt.subplots(3,3,figsize=(12,10));
for ax,p in zip(axs.flat,(0,5,10,15,20,25,30,40,50)):
 img=cv2.imread(str(out/f'occlusion_{p:02}.png')); ax.imshow(cv2.cvtColor(img,cv2.COLOR_BGR2RGB)); item=results[(0,5,10,15,20,25,30,40,50).index(p)]; ax.set_title(f"右侧覆盖 {p}% · {'识别成功' if item['detected'] else '未识别'}"); ax.axis('off')
fig.suptitle('ArUco 合成遮挡对照：灰色区域为右侧遮挡（占标记宽度）',fontsize=15);fig.tight_layout();fig.savefig(out/'synthetic_occlusion_overview.png',dpi=150,bbox_inches='tight');plt.close(fig)
print(json.dumps(results,ensure_ascii=False,indent=2));print('output',out)
