C#中如何通过构造函数为threshold参数设置默认值
阈值参数默认值适配实现方案
1. 改造Threshold类支持构造函数传值/默认值
将原静态工具类改为实例类,通过构造函数重载处理阈值默认逻辑,同时修正原方法无效的二值化处理逻辑:
using System; using System.Collections.Generic; namespace imageprocessing { class Threshold { // 存储实际生效的阈值 private int _thresh; // 预设默认阈值,可根据业务需求调整数值 private const int DefaultThresh = 128; // 无参构造函数:调用时自动使用默认阈值 public Threshold() { _thresh = DefaultThresh; } // 带参构造函数:调用时使用用户传入的自定义阈值 public Threshold(int customThresh) { // 增加参数合法性校验,确保阈值在0-255有效区间内 _thresh = customThresh switch { < 0 => 0, > 255 => 255, _ => customThresh }; } // 对外暴露的阈值处理实例方法 public byte[] ApplyThreshold(byte[] data, int width) { List<byte> processedData = new List<byte>(); byte[] all = data.ToArray(); // 修正原逻辑漏算3通道的问题 for (int j = 0; j < width * 3; j++) { // 修正原逻辑无处理效果的问题:大于阈值设为255(白),小于设为0(黑) processedData.Add(all[j] > _thresh ? (byte)255 : (byte)0); } return processedData.ToArray(); } // 如需对外获取当前使用的阈值可增加此方法 public int GetCurrentThresh() { return _thresh; } } }
2. 改造Form1中的调用逻辑
新增输入合法性判断逻辑,用户未输入/输入非合法数字时自动使用默认阈值:
首先替换Camera_NewFrame方法中原阈值处理的相关代码:
if (btn_thresholdWasClicked == true) { alldata.Clear(); Threshold thresholdProcessor; // 判断输入框是否存在合法数值输入 if (int.TryParse(tb_contrast.Text.Trim(), out int customThresh)) { // 输入合法,使用自定义阈值构造实例 thresholdProcessor = new Threshold(customThresh); } else { // 无输入/输入不合法,使用默认阈值构造实例 thresholdProcessor = new Threshold(); } for (int i = 0; i < image.Height; i++) { int count = 0; for (int j = 0; j < image.Width; j++) { Color color = image.GetPixel(j, i); maindata[count] = color.R; maindata[count + 1] = color.G; maindata[count + 2] = color.B; count += 3; } // 调用实例方法完成阈值处理 byte[] processthreshold = thresholdProcessor.ApplyThreshold(maindata, image.Width); alldata.AddRange(processthreshold); } }
如需保持对比度调节的阈值规则统一,同步修改btn_contrast_Click方法:
private void btn_contrast_Click(object sender, EventArgs e) { Threshold thresholdProcessor; if (int.TryParse(tb_contrast.Text.Trim(), out int customThresh)) { thresholdProcessor = new Threshold(customThresh); } else { thresholdProcessor = new Threshold(); } Contrast.contrast(alldata.ToArray(),1920,thresholdProcessor.GetCurrentThresh()); }
内容的提问来源于stack exchange,提问作者user17097848
相关产品推荐
相关产品推荐

