public Boolean needDown() { ScanImage tmpScanImage = null; string imageID = ""; string fileExt = ""; //图片后缀 string fileName = ""; //本地路径 string filePath = ""; for (int i = 0; i < scanInfo.scanningFileList.Count; i++) { tmpScanImage = scanInfo.scanningFileList[i]; filePath = tmpScanImage.file_path; if ((filePath.ToUpper().IndexOf(".JPG") > -1) || (filePath.ToUpper().IndexOf(".TIF") > -1)) { imageID = getImageID(filePath); if (imageID.Trim() != "") { fileExt = filePath.Substring(filePath.Length - 4); fileName = scanInfo.DirPath + scanInfo.businessArchId + tmpScanImage.image_no + fileExt; tmpScanImage.Local_path = fileName; scanIni.writeLog("NeedDown: FileName=" + fileName); //本地有需更新 if ((!File.Exists(tmpScanImage.file_path)) && (File.Exists(fileName))) { return(true); } if ((!File.Exists(fileName)) || (GetFileSize(fileName) == "0")) { return(true); } } } } return(false); }
private void SetParameters(string inputPath, ScanningMethod scanningMethod, DescriptorMethod descriptorMethod, MachineLearningMethod machineLearningMethod) { _symbolParameters = new Utility.SymbolParameters(); _hessianThreshould = _symbolParameters.HessianThresh; _uniquenessThresh = _symbolParameters.UniquenessThress; _histogramMatchingScore = _symbolParameters.HistogramMatchingScore; _tm = _symbolParameters.TM; _log = File.AppendText(inputPath + "/log.txt"); _machineLearningMethod = machineLearningMethod; _scanningMethod = scanningMethod; _descriptorType = descriptorMethod; //check the FilePath _inputPath = inputPath; _inPath = inputPath + "/in"; _outPath = inputPath + "/out"; _intermediatePath = inputPath + "/Intermediate"; ValidateFilePath(_inPath, "in"); ValidateFilePath(_outPath, "out"); ValidateFilePath(_intermediatePath, "Intermediate"); ValidateFilePath(_inputPath, ""); _descriptor = new Descriptor(); _machineLearning = new MachineLearning(); _scanImage = new ScanImage(); }
public void ScanImage_With_Null_Logger_Raises_Exception() { Action action = () => { var scanImage = new ScanImage(_mockConfiguration.Object, null); }; action.Should().Throw <ArgumentNullException>(); }
private async Task NewMethod() { ScanImage.SetValue(IsVisibleProperty, true); try { if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported) { await DisplayAlert("No Camera", ":( No camera available.", "OK"); return; } else { var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions { Directory = "Sample", Name = "test.jpg", SaveToAlbum = true, }); if (file == null) { return; } if (ScanImage != null) { ScanImage.Source = ImageSource.FromStream(() => { var stream = file.GetStream(); file.Dispose(); return(stream); }); // mainSTack.IsVisible = false; } } var scan = new ZXingScannerPage(); await Navigation.PushAsync(scan); scan.OnScanResult += (result) => { ZXing.BarcodeFormat barcodeFormat = result.BarcodeFormat; string type = barcodeFormat.ToString(); Device.BeginInvokeOnMainThread(async() => { await Navigation.PopAsync(); VinEnteredNumber.Text = result.Text; }); }; }catch (Exception ex) { await DisplayAlert("Alert", " " + ex, "OK"); } }
public void DetectShapes_With_Null_Stream_Raises_Exception() { _mockConfiguration.SetupGet(x => x[It.Is <string>(s => s == "VisionEndpoint")]).Returns(endpoint); _mockConfiguration.SetupGet(x => x[It.Is <string>(s => s == "VisionAccessKey")]).Returns(accessKey); _sut = new ScanImage(_mockConfiguration.Object, _mockLogger.Object); Func <Task <DetectResult> > method = async() => await _sut.DetectShapes(null); method.Should().Throw <ArgumentNullException>(); }
public void ScanImage_With_Null_AccessKey_Raises_Exception() { var accessKey = default(string); var stream = new MemoryStream(); _mockConfiguration.SetupGet(x => x[It.Is <string>(s => s == "VisionEndpoint")]).Returns(endpoint); _mockConfiguration.SetupGet(x => x[It.Is <string>(s => s == "VisionAccessKey")]).Returns(accessKey); Action action = () => { _sut = new ScanImage(_mockConfiguration.Object, _mockLogger.Object); }; action.Should().Throw <ArgumentNullException>(); }
private async void OcrMethodCall() { ScanImage.SetValue(IsVisibleProperty, true); try { if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported) { await DisplayAlert("No Camera", ":( No camera available.", "OK"); return; } else { var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions { Directory = "Sample", Name = "test.jpg", SaveToAlbum = true, }); if (file == null) { return; } if (ScanImage != null) { //lblImagePath.Text = "ImagePath" + file.Path; byte[] testByte = CommonFunctions.ReadStream(file.GetStream()); //////////////////////////// var client = new HttpClient(); var queryString = HttpUtility.ParseQueryString(string.Empty); // Request headers client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "de7609da413944308cde16098d1097f0"); var uri = "https://centralus.api.cognitive.microsoft.com/vision/v2.0/ocr" + queryString; HttpResponseMessage response; // Request body // byte[] byteData = Encoding.UTF8.GetBytes("{testByte}"); using (var content = new ByteArrayContent(testByte)) { content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); response = await client.PostAsync(uri, content); var contents = response.Content.ReadAsStringAsync().Result; Debug.WriteLine("OCR response " + contents); } var responseResult = await response.Content.ReadAsStringAsync(); ocrModel = JsonConvert.DeserializeObject <OcrModel>(responseResult); var wordCount = Convert.ToString(ocrModel.regions[0].lines[0].words.Count); StringBuilder numberList = new StringBuilder(); for (int i = 0; i < ocrModel.regions[0].lines[0].words.Count; i++) { numberList.Append(ocrModel.regions[0].lines[0].words[i].text); numberList.Append(" "); } VinEnteredNumber.Text = numberList.ToString(); Debug.WriteLine("Car Numebr " + numberList.ToString()); ////////////////////////////// ScanImage.Source = ImageSource.FromStream(() => { var stream = file.GetStream(); file.Dispose(); return(stream); }); // mainSTack.IsVisible = false; } } } catch (Exception ex) { await DisplayAlert("Alert", " " + ex, "OK"); } }
private void RadioButton_Clicked_DirectInput(object sender, EventArgs e) { ScanImage.SetValue(IsVisibleProperty, false); // the view is GONE, not invisible VinEnteredNumber.Text = null; VinNumber = VinEnteredNumber.Text; }
public Boolean downImage() { Boolean result = true;//默认下载完成 //临时变量 ScanImage tmpScanImage = null; string imageID = ""; string fileExt = ""; //图片后缀 string fileName = ""; //本地路径 string filePath = ""; string url = ""; for (int i = 0; i < scanInfo.scanningFileList.Count; i++) { tmpScanImage = scanInfo.scanningFileList[i]; filePath = tmpScanImage.file_path; //本地有不下载 if (File.Exists(filePath)) { continue; } if ((filePath.ToUpper().IndexOf(".JPG") > -1) || (filePath.ToUpper().IndexOf(".TIF") > -1)) { imageID = getImageID(filePath); if (imageID.Trim() != "") { fileExt = filePath.Substring(filePath.Length - 4); fileName = scanInfo.DirPath + scanInfo.businessArchId + tmpScanImage.image_no + fileExt; tmpScanImage.Local_path = fileName; scanIni.writeLog("DownImage.image_name=" + tmpScanImage.fileName + ";FileName=" + fileName); try { if (File.Exists(fileName)) { File.Delete(fileName); } } catch (Exception e) { result = false; //不明 btnReset.Visible := True; //pnlFilesTitle.Caption := '下载文件[' + ASourceImage.image_name + '] 失败'; MessageBox.Show("下载图片时删除本地空图片发生异常:" + e.Message, "异常", MessageBoxButton.OK, MessageBoxImage.Warning, new MessageBoxResult()); } if (!File.Exists(fileName)) { try { if (!Directory.Exists(scanInfo.DirPath)) { Directory.CreateDirectory(scanInfo.DirPath); } url = filePath; scanIni.writeLog("DownImage: url=" + url); } catch (Exception e) { result = false; MessageBox.Show("下载文件[" + tmpScanImage.fileName + "] 失败(创建目录失败,路径:" + scanInfo.DirPath + ")", "异常", MessageBoxButton.OK, MessageBoxImage.Warning, new MessageBoxResult()); } //下载图片 DownloadFile(scanIni, url, fileName, 'f'); } } } } return(result); }
//读取配置文件到类 private Boolean LoadXMLData(string xmlstr) { XmlDocument xmldoc = new XmlDocument(); xmldoc.LoadXml(xmlstr); //通过defaul.xsd验证验证xml格式是否正确 string error = ""; XmlSchemaSet schemas = new XmlSchemaSet();//声明XmlSchema schemas.Add("", XmlReader.Create(singlePath + "\\defaul.xsd")); ValidationEventHandler eventHandler = new ValidationEventHandler(delegate(object sender, ValidationEventArgs e) { //声明事件处理方法 switch (e.Severity) { case XmlSeverityType.Error: error += e.Message; break; case XmlSeverityType.Warning: break; } }); xmldoc.Schemas = schemas; //验证xml xmldoc.Validate(eventHandler); if (!"".Equals(error)) { MessageBox.Show("XML验证失败:" + error, "提示", MessageBoxButton.OK); } try { xmldoc.LoadXml(xmlstr);//加载xml文档 } catch (Exception e) { MessageBox.Show("加载xml数据错误:", "提示", MessageBoxButton.OK); return(false); } //HsMessageBox.Show(xmlstr); //begin 解析xml,转为对象列表-------------------------------------------------------------------------------- int count = int.Parse(xmldoc.DocumentElement.Attributes["count"].Value); //采集项个数 scanInfo.branchNo = int.Parse(xmldoc.DocumentElement.Attributes["branchNo"].Value); //分支机构 scanInfo.clientId = "8888"; //客户号 if (xmldoc.DocumentElement.Attributes.GetNamedItem("custCode") != null) { scanInfo.clientId = xmldoc.DocumentElement.Attributes["custCode"].Value; } scanInfo.businessArchId = "";//档案编号 if (xmldoc.DocumentElement.Attributes.GetNamedItem("businessArchId") != null) { scanInfo.businessArchId = xmldoc.DocumentElement.Attributes["businessArchId"].Value; } scanInfo.DirPath = singlePath + "\\image\\" + scanInfo.branchNo + "\\" + scanInfo.clientId + "\\"; //加载到list for (int i = 0; i < count; i++) { XmlNode node = xmldoc.DocumentElement.ChildNodes.Item(i); ScanImage scanImage = new ScanImage(); scanImage.image_no = node.Attributes["archImageNo"].Value;//文件编号 if (scanImage.image_no == null) { scanImage.image_no = ""; } scanImage.fileName = node.Attributes["imageName"].Value;//文件名称 if (scanImage.fileName == null) { continue; } scanImage.image_set = node.Attributes["imageSet"].Value[0]; //图片处理类型:image_set scanImage.image_type = node.Attributes["imageType"].Value[0]; //影像类型:image_type scanImage.image_dpi = int.Parse(node.Attributes["imageDpi"].Value); //图像DPI:image_dpi scanImage.file_size = int.Parse(node.Attributes["fileSize"].Value); //文件大小:file_size scanImage.lower_file_size = int.Parse(node.Attributes["lowFileSize"].Value); //文件大小下限:low_file_size scanImage.have_scan = node.Attributes["haveScan"].Value[0]; //是否必扫:have_scan scanImage.file_path = node.Attributes["filePath"].Value; //file_path if (scanImage.file_path == null) { scanImage.file_path = ""; } scanImage.import_local_flag = node.Attributes["importLocalFlag"].Value[0]; //导入本地图片标志 scanImage.datewater_flag = node.Attributes["datewaterFlag"].Value[0]; //是否加时间水印戳 scanImage.page_num = int.Parse(node.Attributes[("pageNum")].Value); //采集页码数 scanImage.index = int.Parse(node.Attributes["index"].Value); //index string ext = ""; if (scanImage.image_type != '2') { ext = ".tif"; } else { ext = ".jpg"; } if (scanImage.file_path == " ") { scanImage.Local_path = scanInfo.DirPath + scanInfo.businessArchId + scanImage.image_no + ext; if (File.Exists(scanImage.Local_path)) { try { File.Delete(scanImage.Local_path); } catch (Exception e) { MessageBox.Show("删除本地图片错误:" + scanImage.Local_path, "提示", MessageBoxButton.OK); return(false); } } } else { scanImage.Local_path = scanImage.file_path; } scanImage.postfix = ext; //路径为空创建目录 if (!Directory.Exists(singlePath + "\\image\\" + scanInfo.branchNo + "\\" + scanInfo.clientId + "\\")) { try { Directory.CreateDirectory(singlePath + "\\image\\" + scanInfo.branchNo + "\\" + scanInfo.clientId + "\\"); } catch (Exception e) { MessageBox.Show("创建本地目录失败:" + singlePath + "\\image\\" + scanInfo.branchNo + "\\" + scanInfo.clientId + "\\", "提示", MessageBoxButton.OK); return(false); } } //scanImage.IsUpload = true; fileList.Add(scanImage); } scanInfo.scanningFileList = fileList;//注入scanInfo中 return(true); }
public void SymbolRecognitionBySVM(string positivePath, string negativePath, string testPath) { double[][] inputs, testInputs; int[] outputs; Image <Bgr, Byte>[] Positives, Negatives; Image <Bgr, Byte> test; int total = 0; int counter = 0; _scanImage = new ScanImage(); _descriptor = new Descriptor(); _scanImage.SetImages(positivePath, negativePath, testPath, out Positives, out Negatives, out test); if (Negatives != null && Negatives.Length != 0) { total += Negatives.Length; } if (Positives != null && Positives.Length != 0) { total += Positives.Length; } inputs = new double[total][]; outputs = new Int32[total]; if (Negatives != null || Negatives.Length != 0) { for (int i = 0; i < Negatives.Length; i++) { inputs[counter] = _descriptor.GetImageVector(Negatives[i], 100); outputs[counter++] = 0; } } if (Positives != null || Positives.Length != 0) { for (int i = 0; i < Positives.Length; i++) { inputs[counter] = _descriptor.GetImageVector(Positives[i], 100); outputs[counter++] = 1; } } _scanImage.ScanByPixel(@"C:\Users\simakmo\Documents\Sima\Symbol Reconition\data\", test, Positives[0], 50, 50); string[] filePaths = Directory.GetFiles(@"C:\Users\simakmo\Documents\Sima\Symbol Reconition\data\Intermediate", "*.jpg"); testInputs = new double[filePaths.Length][]; counter = 0; foreach (string path in filePaths) { testInputs[counter++] = _descriptor.GetImageVector(new Image <Bgr, Byte>(path), 150); } _machineLearning = new MachineLearning(); int dimention = Positives[0].Height * Positives[0].Width; int[] testOutputs = _machineLearning.ApplySVMByGussianKernel(2, 2.5, 0.001, 0.2, inputs, outputs, dimention, testInputs); List <Point> results = new List <Point>(); for (int j = 0; j < testOutputs.Length; j++) { int x, y, num; if (testOutputs[j] == 1) { GetImageParameters(out x, out y, out num, filePaths[j]); results.Add(new Point(x, y)); } } Visualization.DrawResults(results, Positives[0].Size, test, testPath); }