文章目录org.openpnp.vision.pipeline.stages.ThresholdAdaptive功能参数例子效果ENDorg.openpnp.vision.pipeline.stages.ThresholdAdaptive功能ThresholdAdaptive 是 OpenPnP 视觉管道中的一个自适应阈值二值化阶段用于处理光照不均的图像。与固定阈值 Threshold 不同它根据每个像素邻域的局部特性动态计算阈值从而更好地分离前景和背景。局部阈值计算对每个像素以其为中心的 blockSize × blockSize 邻域内计算均值或加权高斯和减去常数 cParm 得到该像素的阈值。二值化输出将像素值与局部阈值比较大于阈值的设为 255白色否则为 0黑色可选的 invert 参数反转黑白。两种自适应方法Mean邻域均值法。Gaussian邻域加权高斯和法对中心像素权重更高。参数参数名数据类型默认值功能描述adaptiveMethodAdaptiveMethodMean自适应阈值算法。可选值Mean邻域均值、Gaussian邻域加权高斯和。invertbooleanfalse是否反转二值化结果。false前景为白色255背景为黑色0true前景为黑色背景为白色。blockSizeint127计算阈值所用的像素邻域尺寸。必须是奇数且 ≥ 3。实际值会被调整为不小于3的奇数。cParmint80从计算出的局部均值或加权均值中减去的常数。可为负值用于调整阈值灵敏度。例子importcv2importnumpy as np def generate_color_rects_image(output_path):生成彩色背景图像包含多个不同尺寸、颜色、角度的旋转矩形无网格线 width, height800,600imgnp.full((height, width,3),(240,240,240),dtypenp.uint8)# 浅灰色背景# 定义矩形列表(中心x,中心y, 宽w,高h, 角度, 颜色BGR, 标签)rects[(200,150,80,50,30,(0,0,255),R1),# 红色80x50(600,150,60,40, -20,(0,255,0),R2),# 绿色60x40(200,400,100,70,15,(255,0,0),R3),# 蓝色100x70(600,400,90,60, -45,(0,255,255),R4),# 黄色90x60(400,300,120,80,0,(255,255,0),R5),# 青色120x80太大(150,80,30,20,60,(255,0,255),R6),# 紫色30x20太小]for(cx, cy, w, h, angle, color, label)inrects: rect((cx, cy),(w, h), angle)boxcv2.boxPoints(rect)boxnp.array(box,dtypenp.int32)overlayimg.copy()cv2.fillPoly(overlay,[box], color)cv2.addWeighted(overlay,0.6, img,0.4,0, img)cv2.drawContours(img,[box],0,(0,0,0),2)cv2.putText(img, label,(cx-20, cy-10), cv2.FONT_HERSHEY_SIMPLEX,0.5,(0,0,0),1)print(f{label}: 宽{w}, 高{h}, 角度{angle})cv2.imwrite(output_path, img)print(f已生成彩色测试图像: {output_path})if__name____main__:generate_color_rects_image(color_rects_test.png)cv-pipelinestagescv-stageclassorg.openpnp.vision.pipeline.stages.ImageReadnameloadImageenabledtruefileD:\3rd\openpnp_prj\openpnp-official\openpnp-test-images\my_test\color_rects_test.pngcolor-spaceBgrhandle-as-capturedfalse/cv-stageclassorg.openpnp.vision.pipeline.stages.ConvertColornametoGrayenabledtrueconversionBgr2Gray/cv-stageclassorg.openpnp.vision.pipeline.stages.ThresholdAdaptivenameadaptiveBinenabledtrueadaptive-methodMeaninvertfalseblock-size11c-parm50/cv-stageclassorg.openpnp.vision.pipeline.stages.ImageWritenamesaveResultenabledtruefileD:\3rd\openpnp_prj\openpnp-official\openpnp-test-images\my_test\adaptive_result.png//stages/cv-pipeline效果blockSize和cParm都不能太大否则前后背景剥离的效果不好。通过调整blockSize和cParm可以得到非常干净的黑白线图。可以看到使用ThresholdAdaptive比Threshold要更自由。END