332 lines
21 KiB
Python
332 lines
21 KiB
Python
"""Isolated OpenCV worker for Qt. One UTF-8 JSON request/reply per line.
|
||
|
||
Protocol 1 uses row-major 16-element SE(3) matrices, metres and radians.
|
||
T_parent_child transforms child coordinates into parent coordinates. The
|
||
worker never opens cameras or robots: every measurement comes from the caller.
|
||
Detect supports a PNG in image_png_base64 or stride-aware frame planes.
|
||
Solve requires paired T_base_flange/T_camera_target and reprojection_px.
|
||
ok means the operation ran; valid (and metrics.accepted) controls acceptance.
|
||
Phone provenance is listed in handeye_math.py and at the ported stages below.
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import base64
|
||
import json
|
||
import math
|
||
import sys
|
||
from pathlib import Path
|
||
from typing import Any
|
||
|
||
import cv2
|
||
import numpy as np
|
||
|
||
# -I / embedded Python intentionally exclude the working directory and script
|
||
# directory. Only add our explicitly deployed sibling algorithm modules.
|
||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||
from handeye_math import (HAND_EYE_SOLVER_METHODS, dominant_rotation_axes,
|
||
estimate_planar_pose, robust_handeye_calibration, rvec_tvec_to_matrix,
|
||
ax_xb_all_pair_metrics, fixed_target_consistency)
|
||
|
||
PROTOCOL = 1
|
||
MAX_DIMENSION = 8192
|
||
MAX_PIXELS = 32_000_000
|
||
MAX_LINE_BYTES = 180_000_000
|
||
MAX_REPROJECTION_PX = 1.5
|
||
MAX_PHOTO_BYTES = 2 * 1024 * 1024
|
||
|
||
|
||
def capture_photo(image: np.ndarray) -> str:
|
||
# Keep full frame coordinates for the measured corners; never resize.
|
||
for quality in (90, 75, 55, 35):
|
||
ok, encoded = cv2.imencode('.jpg', image, [cv2.IMWRITE_JPEG_QUALITY, quality])
|
||
if ok and encoded.nbytes <= MAX_PHOTO_BYTES:
|
||
return base64.b64encode(encoded).decode('ascii')
|
||
raise ValueError('采样照片编码失败或超过 2 MiB,请降低视频分辨率后重采')
|
||
|
||
|
||
def finite_array(value: Any, shape: tuple[int, ...], name: str) -> np.ndarray:
|
||
result = np.asarray(value, dtype=np.float64)
|
||
if result.size != math.prod(shape) or not np.all(np.isfinite(result)):
|
||
raise ValueError(f'{name}: expected {math.prod(shape)} finite numbers')
|
||
return result.reshape(shape)
|
||
|
||
|
||
def matrix(value: Any, name: str) -> np.ndarray:
|
||
result = finite_array(value, (4, 4), name)
|
||
rotation = result[:3, :3]
|
||
if not np.allclose(result[3], [0,0,0,1], atol=1e-8, rtol=0):
|
||
raise ValueError(f'{name}: invalid homogeneous bottom row')
|
||
if not np.allclose(rotation.T @ rotation, np.eye(3), atol=1e-5, rtol=0) or abs(np.linalg.det(rotation)-1) > 1e-5:
|
||
raise ValueError(f'{name}: rotation must be proper orthonormal SO(3)')
|
||
return result
|
||
|
||
|
||
def dimensions(width: Any, height: Any) -> tuple[int, int]:
|
||
w,h=int(width),int(height)
|
||
if w != width or h != height or min(w,h)<2 or max(w,h)>MAX_DIMENSION or w*h>MAX_PIXELS:
|
||
raise ValueError('Invalid image dimensions (maximum 8192 per axis / 32 megapixels)')
|
||
return w,h
|
||
|
||
|
||
def decode_frame(request: dict) -> np.ndarray:
|
||
w,h=dimensions(request['width'], request['height'])
|
||
if 'frame' not in request:
|
||
encoded=base64.b64decode(request['image_png_base64'],validate=True)
|
||
# Check the PNG header before allowing OpenCV to allocate decoded pixels.
|
||
if len(encoded)<24 or encoded[:8] != b'\x89PNG\r\n\x1a\n':
|
||
raise ValueError('image_png_base64 must contain a PNG image')
|
||
pw,ph=int.from_bytes(encoded[16:20],'big'),int.from_bytes(encoded[20:24],'big')
|
||
if (pw,ph)!=(w,h): raise ValueError('PNG dimensions differ from calibrated width/height')
|
||
image=cv2.imdecode(np.frombuffer(encoded,np.uint8),cv2.IMREAD_COLOR)
|
||
if image is None: raise ValueError('Could not decode PNG image')
|
||
return image
|
||
frame=request['frame']
|
||
if dimensions(frame['width'],frame['height'])!=(w,h):
|
||
raise ValueError('Frame dimensions differ from calibrated width/height')
|
||
fmt=frame['format'];planes=frame['planes']
|
||
count={'RGBA':1,'I420':3,'NV12':2}.get(fmt)
|
||
if count is None or len(planes)!=count: raise ValueError('Unsupported frame format or plane count')
|
||
def plane(index: int, rows: int, row_bytes: int) -> np.ndarray:
|
||
stride=int(frame.get(f'stride{index}',row_bytes))
|
||
if stride<row_bytes or stride>row_bytes+65536: raise ValueError('Invalid plane stride')
|
||
raw=base64.b64decode(planes[index],validate=True)
|
||
# Trailing row padding may be omitted by frame producers.
|
||
minimum=(rows-1)*stride+row_bytes
|
||
if len(raw)<minimum or len(raw)>rows*stride: raise ValueError('Frame plane length does not match dimensions/stride')
|
||
return np.ndarray((rows,row_bytes),dtype=np.uint8,buffer=raw,strides=(stride,1)).copy()
|
||
if fmt=='RGBA': return cv2.cvtColor(plane(0,h,w*4).reshape(h,w,4),cv2.COLOR_RGBA2BGR)
|
||
if w%2 or h%2: raise ValueError('I420/NV12 frames require even dimensions')
|
||
y=plane(0,h,w)
|
||
if fmt=='I420':
|
||
packed=np.concatenate((y.ravel(),plane(1,h//2,w//2).ravel(),plane(2,h//2,w//2).ravel())).reshape(h*3//2,w)
|
||
return cv2.cvtColor(packed,cv2.COLOR_YUV2BGR_I420)
|
||
packed=np.vstack((y,plane(1,h//2,w)))
|
||
return cv2.cvtColor(packed,cv2.COLOR_YUV2BGR_NV12)
|
||
|
||
|
||
def detect(request: dict) -> dict:
|
||
k=finite_array(request['K'],(3,3),'K')
|
||
d=np.asarray(request.get('D',[]),dtype=np.float64).reshape(-1)
|
||
if len(d) not in (0,4,5,8,12,14) or not np.all(np.isfinite(d)):
|
||
raise ValueError('D requires 0, 4, 5, 8, 12 or 14 finite coefficients')
|
||
if k[0,0]<=0 or k[1,1]<=0 or not np.allclose(k[2],[0,0,1],atol=1e-10):
|
||
raise ValueError('Invalid calibrated camera matrix')
|
||
image=decode_frame(request)
|
||
gray=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
|
||
config=request['board'];kind=config['type']
|
||
cols,rows=int(config['columns']),int(config['rows'])
|
||
square=float(config['square_size_m'])
|
||
if not 3<=cols<=100 or not 3<=rows<=100 or not math.isfinite(square) or square<=0:
|
||
raise ValueError('Board requires 3..100 columns/rows and positive square_size_m')
|
||
# Port of phone HandEyeApp.detect (1905-1952), object-point layout
|
||
# (1644-1650), and _board (1584-1597), with stricter boundary validation.
|
||
if kind=='chessboard':
|
||
found,corners=False,None
|
||
try:
|
||
found,corners=cv2.findChessboardCornersSB(gray,(cols,rows),flags=cv2.CALIB_CB_EXHAUSTIVE|cv2.CALIB_CB_ACCURACY)
|
||
except (AttributeError,cv2.error):
|
||
pass
|
||
if not found:
|
||
found,corners=cv2.findChessboardCorners(gray,(cols,rows),flags=cv2.CALIB_CB_ADAPTIVE_THRESH|cv2.CALIB_CB_NORMALIZE_IMAGE)
|
||
if found:
|
||
corners=cv2.cornerSubPix(gray,corners,(5,5),(-1,-1),(cv2.TERM_CRITERIA_EPS|cv2.TERM_CRITERIA_MAX_ITER,40,1e-3))
|
||
if not found or corners is None or len(corners)!=cols*rows:
|
||
return dict(ok=True,valid=False,error=f'未检测到 {cols}×{rows} 棋盘格内角点',corners=[],axes=[],quality_flags=['board_not_found'])
|
||
obj=np.zeros((cols*rows,3),np.float64)
|
||
obj[:,:2]=np.mgrid[0:cols,0:rows].T.reshape(-1,2)*square
|
||
img=np.asarray(corners,np.float64).reshape(-1,2)
|
||
ids=np.arange(len(img))
|
||
elif kind=='charuco':
|
||
marker=float(config['marker_size_m']);name=config.get('dictionary','DICT_4X4_50')
|
||
if not math.isfinite(marker) or not 0<marker<square:
|
||
raise ValueError('marker_size_m must be positive and smaller than square_size_m')
|
||
if not isinstance(name,str) or not name.startswith('DICT_') or not hasattr(cv2.aruco,name):
|
||
raise ValueError('Unknown ArUco dictionary')
|
||
dictionary=cv2.aruco.getPredefinedDictionary(getattr(cv2.aruco,name))
|
||
board=cv2.aruco.CharucoBoard((cols,rows),square,marker,dictionary)
|
||
corners,ids,_,_=cv2.aruco.CharucoDetector(board).detectBoard(gray)
|
||
if ids is None or len(ids)<6:
|
||
return dict(ok=True,valid=False,error='至少需要 6 个 ChArUco 角点',corners=[] if corners is None else corners.reshape(-1,2).tolist(),axes=[],quality_flags=['insufficient_corners'])
|
||
obj,img=board.matchImagePoints(corners,ids)
|
||
obj=np.asarray(obj,np.float64).reshape(-1,3);img=np.asarray(img,np.float64).reshape(-1,2)
|
||
else: raise ValueError('board.type must be chessboard or charuco')
|
||
rvec,tvec=estimate_planar_pose(obj,img,k,d)
|
||
target=rvec_tvec_to_matrix(rvec,tvec)
|
||
projected=cv2.projectPoints(obj,rvec,tvec,k,d)[0].reshape(-1,2)
|
||
error=float(np.mean(np.linalg.norm(projected-img,axis=1)))
|
||
axis=square*2
|
||
axes=cv2.projectPoints(np.array([[0,0,0],[axis,0,0],[0,axis,0],[0,0,axis]],np.float64),rvec,tvec,k,d)[0].reshape(-1,2)
|
||
valid=math.isfinite(error) and error<=MAX_REPROJECTION_PX
|
||
result = dict(ok=True,valid=valid,T_camera_target=target.ravel().tolist(),corners=img.tolist(),ids=np.asarray(ids).ravel().tolist(),axes=axes.tolist(),reprojection_px=error,quality_flags=[] if valid else ['high_reprojection'],error='' if valid else '重投影误差超过 1.5 px',board_type=kind,
|
||
image_points=img.tolist(),object_points=obj.tolist(),corner_ids=np.asarray(ids).ravel().tolist(),
|
||
K=k.ravel().tolist(),D=d.tolist(),width=int(image.shape[1]),height=int(image.shape[0]))
|
||
if valid and request.get('capture_photo') is True:
|
||
result['photo_jpeg'] = capture_photo(image)
|
||
return result
|
||
|
||
|
||
def observable(robots: list[np.ndarray]) -> bool:
|
||
# Rotation vectors must span two independent axes, rather than two bins
|
||
# for one diagonal axis. Translation solve also needs full rank.
|
||
vectors=[];translation_blocks=[]
|
||
for i in range(len(robots)-1):
|
||
for j in range(i+1,len(robots)):
|
||
rotation=robots[i][:3,:3].T @ robots[j][:3,:3]
|
||
vector=cv2.Rodrigues(rotation)[0].ravel()
|
||
if np.linalg.norm(vector)>=math.radians(3): vectors.append(vector)
|
||
translation_blocks.append(rotation-np.eye(3))
|
||
if len(vectors)<2: return False
|
||
values=np.linalg.svd(np.asarray(vectors),compute_uv=False)
|
||
motion_values=np.linalg.svd(np.vstack(translation_blocks),compute_uv=False)
|
||
return bool(values[1]>.03*values[0] and motion_values[-1]>.03*motion_values[0])
|
||
|
||
|
||
def solve(request: dict) -> dict:
|
||
optimization=request.get('optimization','pose_only')
|
||
if optimization not in ('pose_only','joint_reprojection'):
|
||
raise ValueError('Unknown optimization; expected pose_only or joint_reprojection')
|
||
mode={'EyeInHand':'eye_in_hand','EyeToHand':'eye_to_hand'}.get(request.get('mode'),request.get('mode'))
|
||
if mode not in ('eye_in_hand','eye_to_hand'): raise ValueError('Unknown hand-eye mode')
|
||
method=request.get('method','auto')
|
||
if method!='auto' and method not in HAND_EYE_SOLVER_METHODS: raise ValueError('Unknown hand-eye solver')
|
||
samples=request['samples']
|
||
if not isinstance(samples,list) or not 5<=len(samples)<=100:
|
||
raise ValueError('手眼标定需要 5 到 100 组配对位姿,建议至少 12 组')
|
||
robots=[];targets=[];errors=[]
|
||
for index,sample in enumerate(samples):
|
||
robots.append(matrix(sample['T_base_flange'],f'samples[{index}].T_base_flange'))
|
||
target=matrix(sample['T_camera_target'],f'samples[{index}].T_camera_target')
|
||
if target[2,3]<=0: raise ValueError(f'samples[{index}]: board origin must have positive camera depth')
|
||
targets.append(target)
|
||
error=float(sample['reprojection_px'])
|
||
if not math.isfinite(error) or error<0: raise ValueError('Every sample requires finite nonnegative reprojection_px')
|
||
errors.append(error)
|
||
if not observable(robots): raise ValueError('姿态变化不足:需要至少两个独立旋转轴(超过 3°)')
|
||
# Phone reprojection MAD filtering (2712-2748), but never retain a
|
||
# >1.5px observation merely to reach the mathematical minimum.
|
||
median=float(np.median(errors));mad=float(np.median(np.abs(np.asarray(errors)-median)))
|
||
limit=min(MAX_REPROJECTION_PX,max(.65,median+3.5*1.4826*mad))
|
||
original=[i for i,e in enumerate(errors) if e<=limit]
|
||
if len(original)<5: raise ValueError('重投影质量合格样本不足 5 个(上限 1.5 px)')
|
||
selected_robots=[robots[i] for i in original]
|
||
if not observable(selected_robots): raise ValueError('剔除重投影异常后姿态变化不足')
|
||
result=robust_handeye_calibration(selected_robots,[targets[i] for i in original],mode=='eye_in_hand',method)
|
||
active=[original[i] for i in result['active_indices']]
|
||
final=matrix(result['solution'],'solution')
|
||
consistency=result['consistency'];pairs=result['pair_metrics']
|
||
quality=[]
|
||
if not observable([robots[i] for i in active]): quality.append('insufficient_rotation_excitation')
|
||
# Phone's independent validation gates (3085-3094): 5 mm / 2 degrees.
|
||
if pairs['translation_rms_m']>.005: quality.append('high_ax_xb_translation')
|
||
if pairs['rotation_rms_rad']>math.radians(2): quality.append('high_ax_xb_rotation')
|
||
if consistency['translation_max_m']>.005: quality.append('high_fixed_target_translation')
|
||
if consistency['rotation_max_rad']>math.radians(2): quality.append('high_fixed_target_rotation')
|
||
cv=result['solver_reports'][result['selected_solver']].get('leave_one_out')
|
||
if cv is not None:
|
||
if cv['translation_max_m']>.005: quality.append('high_cross_validation_translation')
|
||
if cv['rotation_max_rad']>math.radians(2): quality.append('high_cross_validation_rotation')
|
||
if cv['sample_count']!=len(active): quality.append('incomplete_cross_validation')
|
||
metrics=dict(accepted=not quality,reprojection_mean_px=float(np.mean([errors[i] for i in active])),reprojection_max_px=max(errors[i] for i in active),ax_xb_translation_rms_m=pairs['translation_rms_m'],ax_xb_rotation_rms_rad=pairs['rotation_rms_rad'],fixed_target_translation_max_m=consistency['translation_max_m'],fixed_target_rotation_max_rad=consistency['rotation_max_rad'],pair_count=pairs['pair_count'],samples_total=len(samples),samples_used=len(active))
|
||
active_set=set(active)
|
||
rejected=sorted(set(range(len(samples)))-active_set)
|
||
details=[]
|
||
for i in range(len(samples)):
|
||
detail=dict(input_index=i,used=i in active_set,reprojection_px=errors[i])
|
||
if i in active_set:
|
||
local=active.index(i)
|
||
detail.update(fixed_pose_translation_error_m=float(consistency['translation_errors_m'][local]),fixed_pose_rotation_error_rad=float(consistency['rotation_errors_rad'][local]))
|
||
else: detail['reason']='reprojection_outlier' if i not in original else 'transform_outlier'
|
||
details.append(detail)
|
||
response=dict(ok=True,valid=not quality,mode=mode,matrix=final.ravel().tolist(),matrix_name='T_flange_camera' if mode=='eye_in_hand' else 'T_base_camera',selected_solver=result['selected_solver'],active_indices=active,rejected_indices=rejected,sample_diagnostics=details,metrics=metrics,quality_flags=quality,ax_xb_all_pair_metrics=pairs,fixed_target_consistency={k:v for k,v in consistency.items() if not isinstance(v,np.ndarray)},solver_evaluations=result['solver_reports'],rotation_axis_coverage=sorted(dominant_rotation_axes([robots[i] for i in active])),reprojection_limit_px=limit,independent_validation_required=True,error='' if not quality else '标定质量未通过:'+', '.join(quality),optimization=optimization)
|
||
if optimization=='pose_only':
|
||
return response
|
||
# This is a new joint reprojection stage, not a claim that the phone GUI
|
||
# originally performed Robot-world calibration. Both fixed transforms are
|
||
# variables; robot poses and each observation's intrinsics remain measured.
|
||
from handeye_refinement import refine_joint
|
||
if len(active)<6:
|
||
raise ValueError('联合标定需要至少 6 组有效样本,以进行独立留出验证')
|
||
active_robots=[robots[i] for i in active]
|
||
active_targets=[targets[i] for i in active]
|
||
refinement=refine_joint(active_robots,[samples[i] for i in active],final,mode=='eye_in_hand')
|
||
refined=matrix(refinement['matrix'],'refined solution')
|
||
pairs=ax_xb_all_pair_metrics(active_robots,active_targets,refined,mode=='eye_in_hand')
|
||
consistency=fixed_target_consistency(active_robots,active_targets,refined,mode=='eye_in_hand')
|
||
refined_quality=list(refinement.get('quality_flags',[]))
|
||
if not refinement.get('converged'): refined_quality.append('joint_optimization_not_converged')
|
||
if not refinement.get('accepted') and not refined_quality: refined_quality.append('joint_quality_rejected')
|
||
if pairs['translation_rms_m']>.005: refined_quality.append('high_ax_xb_translation')
|
||
if pairs['rotation_rms_rad']>math.radians(2): refined_quality.append('high_ax_xb_rotation')
|
||
if consistency['translation_max_m']>.005: refined_quality.append('high_fixed_target_translation')
|
||
if consistency['rotation_max_rad']>math.radians(2): refined_quality.append('high_fixed_target_rotation')
|
||
refinement['quality_flags']=sorted(set(refined_quality))
|
||
refinement['accepted']=not refined_quality
|
||
refinement['metrics']['accepted']=not refined_quality
|
||
refined_metrics=dict(metrics)
|
||
refined_metrics.update(accepted=not refined_quality,
|
||
ax_xb_translation_rms_m=pairs['translation_rms_m'],ax_xb_rotation_rms_rad=pairs['rotation_rms_rad'],
|
||
fixed_target_translation_max_m=consistency['translation_max_m'],fixed_target_rotation_max_rad=consistency['rotation_max_rad'],
|
||
joint_reprojection_rms_px=refinement['metrics']['final_rms_px'],
|
||
validation_reprojection_rms_px=refinement['metrics']['validation_rms_px'])
|
||
# Preserve sample indices in the original capture list, including removals
|
||
# made by the phone's robust initialization stage.
|
||
refined_details=refinement.get('sample_diagnostics',[])
|
||
for detail in refined_details:
|
||
detail['input_index']=active[detail['input_index']]
|
||
for fold in refinement.get('validation_folds',[]):
|
||
for field in ('train_indices','held_out_indices'):
|
||
fold[field]=[active[i] for i in fold[field]]
|
||
for local,index in enumerate(active):
|
||
details[index]['fixed_pose_translation_error_m']=float(consistency['translation_errors_m'][local])
|
||
details[index]['fixed_pose_rotation_error_rad']=float(consistency['rotation_errors_rad'][local])
|
||
if local<len(refined_details): details[index]['joint']=refined_details[local]
|
||
refinement['active_indices']=active
|
||
response.update(matrix=refined.ravel().tolist(),refinement=refinement,
|
||
valid=not refined_quality,quality_flags=refinement['quality_flags'],metrics=refined_metrics,
|
||
initial_metrics=metrics,ax_xb_all_pair_metrics=pairs,
|
||
fixed_target_consistency={k:v for k,v in consistency.items() if not isinstance(v,np.ndarray)},
|
||
error='' if not refined_quality else '联合标定质量未通过:'+', '.join(refinement['quality_flags']))
|
||
return response
|
||
|
||
|
||
def handle_request(request: Any) -> dict:
|
||
try:
|
||
if not isinstance(request,dict): raise ValueError('Request must be a JSON object')
|
||
operation=request.get('op')
|
||
if operation=='check':
|
||
# Import here as well so a partial deployment fails during preflight,
|
||
# before users spend time collecting samples.
|
||
from handeye_refinement import refine_joint
|
||
result=dict(ok=True,valid=True,protocol=PROTOCOL,opencv_version=cv2.__version__,numpy_version=np.__version__,methods=['auto',*HAND_EYE_SOLVER_METHODS],capabilities=['chessboard','charuco','eye_in_hand','eye_to_hand','RGBA','I420','NV12','joint_reprojection','raw_corner_observations'],matrix_convention='T_parent_child; row-major; metres')
|
||
elif operation=='detect': result=detect(request)
|
||
elif operation=='solve': result=solve(request)
|
||
else: raise ValueError('Unknown op; expected check, detect or solve')
|
||
except Exception as exc:
|
||
result=dict(ok=False,valid=False,error=str(exc),quality_flags=['operation_failed'])
|
||
result.setdefault('protocol',PROTOCOL)
|
||
if isinstance(request,dict) and 'id' in request: result['id']=request['id']
|
||
return result
|
||
|
||
|
||
def main() -> None:
|
||
# cv2 diagnostics go to stderr; stdout remains strictly NDJSON.
|
||
if hasattr(sys.stdin,'reconfigure'): sys.stdin.reconfigure(encoding='utf-8')
|
||
if hasattr(sys.stdout,'reconfigure'): sys.stdout.reconfigure(encoding='utf-8')
|
||
cv2.setNumThreads(2)
|
||
while True:
|
||
line=sys.stdin.readline(MAX_LINE_BYTES+1)
|
||
if not line: break
|
||
if len(line)>MAX_LINE_BYTES:
|
||
# Discard this request's tail, then accept the next line.
|
||
while line and not line.endswith('\n'): line=sys.stdin.readline(MAX_LINE_BYTES+1)
|
||
result=dict(ok=False,valid=False,protocol=PROTOCOL,error='Request exceeds size limit')
|
||
else:
|
||
try: result=handle_request(json.loads(line))
|
||
except (ValueError,TypeError) as exc: result=dict(ok=False,valid=False,protocol=PROTOCOL,error='Invalid JSON: '+str(exc))
|
||
try: output=json.dumps(result,ensure_ascii=False,allow_nan=False,separators=(',',':'))
|
||
except ValueError: output=json.dumps(dict(ok=False,valid=False,protocol=PROTOCOL,error='Nonfinite algorithm result'))
|
||
print(output,flush=True)
|
||
|
||
|
||
if __name__=='__main__': main()
|