private void Frm_VistaVehiculos_Load(object sender, EventArgs e) { SqlParameter[] Parametros_Consulta = new SqlParameter[4]; Parametros_Consulta[0] = new SqlParameter("@Op", "VehiculosEspe"); Parametros_Consulta[1] = new SqlParameter("@ParametroChar", this.Placa); Parametros_Consulta[2] = new SqlParameter("@ParametroInt", "0"); Parametros_Consulta[3] = new SqlParameter("@ParametroNuemric", "0"); ConsultaEntidades Maestro = new ConsultaEntidades(); Ent_Vehiculo Reader = new Ent_Vehiculo(); Reader = Maestro.Vehiculo("SpConsulta_Tablas", Parametros_Consulta); this.TxbPlaca.Text = Reader.Placa; this.ChbEstado.Checked = Reader.Estado; this.TxbLicencia.Text = Reader.Licencia; this.TxbNombrePropietario1.Text = Reader.NombrePropietario; this.TxbModelo1.Text = Reader.Modelo; this.TxbMarca1.Text = Reader.Marca; this.TxbCilindraje1.Text = Reader.Cilindraje.ToString("###,###,##0.#0").Trim(); this.CmbTipoVehiculo1.SelectedIndex = Reader.TipoVehiculo; this.TxbCombustible1.Text = Reader.Combustible; this.TxbClase1.Text = Reader.Clase; this.TxbCapacidad1.Text = Reader.Peso.ToString("###,###,##0.#0").Trim(); this.TxbMotor1.Text = Reader.Motor; this.TxbDetalle.Text = Reader.Descripcion; this.ptbVehiculo.Image = ImageConvert.byteToImage(Reader.Foto); }
public void SelectImage() { imageRaw.texture = DeviceCameraController.screenshot_tex; string _selectedImageData = ImageConvert.Convert(DeviceCameraController.screenshot_tex); AnnotateImage(_selectedImageData); }
private void Set(RibbonPage page, Item item) { page.Name = item.Name; page.Text = item.Text; if (item.ShowImage == true) { if (item.IsLarge == true) { page.Image = ImageConvert.ConvertToImage(item.LargeImage); if (page.Image == null) { page.Image = ImageConvert.ConvertToImage(item.Image); } } else { page.Image = ImageConvert.ConvertToImage(item.Image); if (page.Image == null) { page.Image = ImageConvert.ConvertToImage(item.LargeImage); } } } else { page.Image = null; } page.Tag = item; }
public static void Execute(AgentHost agentHost, ListBox lstMessage, Panel pnl3x3, Panel pnlDiagData, PictureBox pictureBoxMineCraft, CheckBox chkFullDebug) { WorldState worldState; JavaScriptSerializer json_serializer = new JavaScriptSerializer(); agentHost.setObservationsPolicy(ObservationsPolicy.LATEST_OBSERVATION_ONLY); agentHost.setVideoPolicy(VideoPolicy.LATEST_FRAME_ONLY); // main loop: do { // Get Worldstate worldState = agentHost.getWorldState(); Thread.Sleep(500); // Make an Observation Observation objObservation = RunMission.LogMission(worldState, lstMessage, pnl3x3, pnlDiagData, chkFullDebug); if (worldState.is_mission_running && worldState.video_frames.Count > 0) { // Converts the Malmo ByteVector to a Bitmap and display in pictureBoxMineCraft pictureBoxMineCraft.Image = ImageConvert.GetImageFromByteArray(worldState.video_frames[0].pixels); pictureBoxMineCraft.Invalidate(); pictureBoxMineCraft.Refresh(); } }while (worldState.is_mission_running); lstMessage.Items.Insert(0, "Mission has stopped."); }
public void MotionSensor_2b_threshold() { MotionSensor_2b motion = new MotionSensor_2b(); motion.settings = new MotionSensorSettings(); motion.settings.LoadDefaults(); motion.ControlImageNumber = 10; foreach (var file in Directory.EnumerateFiles(@"d:\bsc\project\TestImages")) { ByteWrapper wrapper = ImageConvert.ReturnByteWrapper(file); motion.ImageCreatedAsync(wrapper, EventArgs.Empty); Thread.Sleep(250); } Assert.IsNotNull(motion.ThresholdImage); for (int i = 0; i < motion.ThresholdImage.Columns.Count; i++) { for (int n = 0; n < motion.ThresholdImage.Columns[i].grids.Count; n++) { Assert.IsTrue(motion.ThresholdImage.Columns[i].grids[n].threshold != 0); } } }//MotionSensor_2b_threshold
private void listComparisonRecord_MouseDoubleClick(object sender, RoutedEventArgs e) { ThriftServiceNameSpace.ThriftService thirft = new ThriftServiceNameSpace.ThriftService(); MyCmpFaceLogWidthImgModel cmpFaceLogWidthImg = listComparisonRecord.SelectedItem as MyCmpFaceLogWidthImgModel; if (cmpFaceLogWidthImg != null) { if (!isHeader) { try { List <byte[]> senceImg = thirft.QuerySenceImg(cmpFaceLogWidthImg.ID, cmpFaceLogWidthImg.date.Split(' ')[0].Replace(@"/", "").Replace(@"/", "")); if (senceImg != null && senceImg.Count > 0 && senceImg[0].Length > 0) { CompInfo comInfoWin = new CompInfo(); BitmapImage bitImage = ImageConvert.ToBitmapImage(senceImg[0]); comInfoWin.SetCmpInfo(cmpFaceLogWidthImg.SnapImage, cmpFaceLogWidthImg.T1.TemplateImage, bitImage, cmpFaceLogWidthImg.score, cmpFaceLogWidthImg.T1.UserName, cmpFaceLogWidthImg.type, cmpFaceLogWidthImg.date + " " + cmpFaceLogWidthImg.time, cmpFaceLogWidthImg.channelName); comInfoWin.Show(); } else { MB_MODULES.Views.MyMessage.showYes("获取抓拍实时帧失败!"); } } catch (Exception ex) { MB_MODULES.Views.MyMessage.showYes(ex.Message); Logger <OperaExcel> .Log.Error("listComparisonRecord_MouseDoubleClick", ex); } } } }
public static Bitmap Gaussian(Bitmap bmp, double sigma) { int width, height; int[][][] img, newImg; Bitmap newBmp; ImageConvert.Bitmap2MatColor(bmp, out img, out width, out height); newImg = new int[3][][]; int n = 4; ConvKernel kernel = Util.GetGaussianKernal(sigma, n); Convolution conv = new Convolution(); // RGB conv.Calculate(img[0], kernel, out newImg[0]); conv.Calculate(img[1], kernel, out newImg[1]); conv.Calculate(img[2], kernel, out newImg[2]); ImageConvert.Mat2BitmapColor(newImg, width, height, out newBmp); return(newBmp); }
/// <summary> /// foamliu, 2009/03/03, 边缘锐化. /// 从原图像中减去拉普拉斯算子处理后的结果. /// 我做的效果是图像锐化的同时产生了噪音. 与这个结果类似: /// /// http://www.dfanning.com/ip_tips/sharpen.html /// /// </summary> /// <param name="bmp"></param> /// <param name="type"></param> /// <returns></returns> public static Bitmap SharpenEdges(Bitmap bmp) { int width, height; int[][][] mat, filtered = new int[3][][]; Bitmap newBmp; ImageConvert.Bitmap2MatColor(bmp, out mat, out width, out height); Convolution conv = new Convolution(); conv.Calculate(mat[0], ConvKernel.Laplacian_4, out filtered[0]); conv.Calculate(mat[1], ConvKernel.Laplacian_4, out filtered[1]); conv.Calculate(mat[2], ConvKernel.Laplacian_4, out filtered[2]); NcvMatrix.MatSubtract(mat[0], filtered[0]); NcvMatrix.MatSubtract(mat[1], filtered[1]); NcvMatrix.MatSubtract(mat[2], filtered[2]); GrayScaleImageLib.Normalize(mat[0]); GrayScaleImageLib.Normalize(mat[1]); GrayScaleImageLib.Normalize(mat[2]); ImageConvert.Mat2BitmapColor(mat, width, height, out newBmp); return(newBmp); }
private void btn_Update_Click(object sender, EventArgs e) { if (edt_Ten.Text.Trim() != "" && edt_LoaiLop.Text.Trim() != "" && edt_DongCo.Text.Trim() != "" && edt_DungTich.Text.Trim() != "" && edt_Gia.Text.Trim() != "" && edt_KichThuoc.Text.Trim() != "" && edt_PhanhSau.Text.Trim() != "" && edt_PhanhTruoc.Text.Trim() != "" && edt_KhoiLuong.Text.Trim() != "" && edt_Momen.Text.Trim() != "") { Data_Entity.DanhMuc_Data.Edit_DanhMuc(new DanhMuc() { id_DanhMuc = edt_Ma.Text, name_DanhMuc = edt_Ten.Text, breakend_DanhMuc = edt_PhanhSau.Text, breakfont_DanhMuc = edt_PhanhTruoc.Text, engine_DanhMuc = edt_DongCo.Text, size_DanhMuc = edt_KichThuoc.Text, price_DanhMuc = int.Parse(edt_Gia.Text), volume_DanhMuc = edt_DungTich.Text, tire_DanhMuc = edt_LoaiLop.Text, torque_DanhMuc = edt_Momen.Text, weight_DanhMuc = int.Parse(edt_KhoiLuong.Text), id_BaoHanh = cbb_BaoHanh.SelectedValue.ToString(), id_HangSX = cbb_Hang.SelectedValue.ToString(), id_LoaiSP = cbb_Loai.SelectedValue.ToString(), image_DanhMuc = ImageConvert.ConvertImageToBinary(this.ptb_HinhAnh.Image) }); MessageBox.Show("The object is Updated!", "Note", MessageBoxButtons.OK); this.edt_Ma.Text = Create_ID.Gennaral_ID(Data_Entity.DanhMuc_Data.Get_IdDanhMuc()); } else { MessageBox.Show("The fields is not Null!", "Note", MessageBoxButtons.OK); } }
private async void GetPlanUser() { IsBusy = true; ListPlanes = new ObservableCollection <PlanEntrenamiento>(); ListPlanes.Clear(); ServiceClient client = new ServiceClient(); DbContext db = new DbContext(); var result = db.GetUsuario(); var query = $"pnl/spapp/ws_planentrenamiento_vigente?client={result.Client}&socio={result.IdUser}"; var response = await client.GetListAllWithParam <List <PlanEntrenamiento> >(Configuration.BaseUrl, query); if (response != null) { if (response.Count > 0) { foreach (var items in response) { items.ImageBase = ImageConvert.ConvertToBase(items.Foto); ListPlanes.Add(items); } } else { App.MessageError("No hay datos"); } } else { App.MessageError("Intentelo mas tarde"); } IsBusy = false; }
private async void GetEntrenamiento() { IsBusy = true; ListEjercicios = new ObservableCollection <PlanEntrenamientoEjercicios>(); ListEjercicios.Clear(); ServiceClient client = new ServiceClient(); DbContext db = new DbContext(); var result = db.GetUsuario(); var query = $"pnl/spapp/ws_planentrenamiento_planes_ejercicios?client={result.Client}&socio={result.IdUser}&id={_idPlan}&tipo={_subPlan.Tipo}"; var response = await client.GetListAllWithParam <List <PlanEntrenamientoEjercicios> >(Configuration.BaseUrl, query); if (response != null) { if (response.Count > 0) { foreach (var item in response) { item.ImageConvert = ImageConvert.ConvertToBase(item.Photo); ListEjercicios.Add(item); } } else { App.MessageError("No hay datos"); } } else { App.MessageError("Intentelo mas tarde"); } IsBusy = false; }
private void Set_UI() { cbb_Loai.DataSource = LoaiSP_Data.Get_LoaiSpList(); cbb_Loai.ValueMember = "id_LoaiSP"; cbb_Loai.DisplayMember = "name_LoaiSP"; cbb_BaoHanh.DataSource = BaoHanh_Data.Get_BaoHanhList(); cbb_BaoHanh.DisplayMember = "lim_BaoHanh"; cbb_BaoHanh.ValueMember = "id_BaoHanh"; cbb_Hang.DataSource = HangSX_Data.Get_HangSXList(); cbb_Hang.ValueMember = "id_HangSX"; cbb_Hang.DisplayMember = "name_HangSX"; DanhMuc danhMuc = DanhMuc_Data.Get_DanhMuc(this.id); edt_Ma.Text = danhMuc.id_DanhMuc; edt_Ten.Text = danhMuc.name_DanhMuc; edt_PhanhSau.Text = danhMuc.breakend_DanhMuc; edt_PhanhTruoc.Text = danhMuc.breakfont_DanhMuc; edt_DongCo.Text = danhMuc.engine_DanhMuc; edt_KichThuoc.Text = danhMuc.size_DanhMuc; edt_Gia.Text = danhMuc.price_DanhMuc.ToString(); edt_DungTich.Text = danhMuc.volume_DanhMuc; edt_LoaiLop.Text = danhMuc.tire_DanhMuc; edt_Momen.Text = danhMuc.torque_DanhMuc; edt_KhoiLuong.Text = danhMuc.weight_DanhMuc.ToString(); ptb_HinhAnh.Image = ImageConvert.ConvertBinaryToImage(danhMuc.image_DanhMuc); cbb_Loai.SelectedValue = danhMuc.id_LoaiSP; cbb_Hang.SelectedValue = danhMuc.id_HangSX; cbb_BaoHanh.SelectedValue = danhMuc.id_BaoHanh; }
public void SetIdentifyResults(IdentifyResults _IdentifyResults) { try { image_capImage.Source = _IdentifyResults.CapImg; image_cmpImage.Source = _IdentifyResults.RegImg; long _longtime = _IdentifyResults.NewRci.Time; DateTime s = new DateTime(1970, 1, 1); s = s.AddSeconds(_longtime); label_Socre.Text = label_Socre.Text.ToString().Replace("Socre", _IdentifyResults.NewRci.Score + ""); label_TemplateName.Text = label_TemplateName.Text.ToString().Replace("TemplateName", _IdentifyResults.NewRci.Name); label_TemplateType.Text = label_TemplateType.Text.ToString().Replace("TemplateType", _IdentifyResults.TemplateType); label_CapTime.Text = s.ToString("yyyy/MM/dd HH:mm:ss"); label_CapChannel.Text = label_CapChannel.Text.ToString().Replace("CapChannel", _IdentifyResults.ChannelName); List <byte[]> senceImg = thirft.QuerySenceImg(_IdentifyResults.ID, s.ToString("yyyy/MM/dd HH:mm:ss").Split(' ')[0].Replace("/", "").Replace("/", "")); if (senceImg != null && senceImg.Count > 0 && senceImg[0].Length > 0) { image_SenceImg.Source = ImageConvert.ToBitmapImage(senceImg[0]); } else { MB_MODULES.Views.MyMessage.showYes("获取抓拍实时帧失败!"); } } catch (Exception ex) { MyMessage.Show(ex.Message); } }
public ConnectedComponents(Bitmap bmp) { m_bmp = bmp; ImageConvert.Bitmap2Mat(bmp, out m_img, out m_width, out m_height); m_newImg = Util.BuildMatInt(m_width, m_height); }
public MediaManager() { _vpxDecoder = new VPXEncoder(); _vpxDecoder.InitDecoder(); _imageConverter = new ImageConvert(); }
private void ImportImageCommandFunc(object obj) { Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); dlg.Filter = "图片|*.jpg;*.png;*.bmp;*.jpeg"; Nullable <bool> result = dlg.ShowDialog(); if (result == true) { string filename = dlg.FileName; if (filename != prexPhoto) { string toptipMsg = string.Empty; if (ZhangXiaowen.GetFileSize(filename, SizeUnits.KByte, ref toptipMsg) < 500) { SearchSchemaDatas.ImportImageByteArray = ImageConvert.ToImageStream(filename); BitmapImage selectedImg = new BitmapImage(new Uri(filename)); SearchSchemaDatas.ImportImage = selectedImg; OnPropertyChanged("SearchSchemaDatas"); } else { MyMessage.Show("当前文件" + toptipMsg + "\n文件不能大于500KB"); } } } }
public CommonResult <string> Base64ToImage(ImageConvert Model) { CommonResult <string> res = ImageBase64Convert <string> .Base64StringToImage(Model.Name, Model.ImageBase64Str); if (res.Code == Code.Success) { //插入数据库 Client client = new Client(); client.Name = Model.Name; client.Avator = res.Message; object obj = db.Insert("client_info", "Id", client); if ((int)obj > 0) { Console.WriteLine("新增成功"); } else { Console.WriteLine("新增失败"); } } return(res); }
public async Task <string> PerformAnnotation(Texture2D snap) { var frameBreak = new WaitForEndOfFrame(); if (RescaleInput) { snap = GenericUtils.Resize(snap, (int)scaleResolution.x, (int)scaleResolution.y); } _width = snap.width; _height = snap.height; // Convert to base64 encoding. string _selectedImageData = ImageConvert.Convert(snap); if (MasoutisManager.category == (int)Enums.MasoutisCategories.product) { AnnotateImage(_selectedImageData, productFeatureTypes); } else { AnnotateImage(_selectedImageData, shelfFeatureTypes); } while (annotationCompleted != true) { await frameBreak; } return(textAnnotation); }
private void Set(RibbonPageGroup group, Item item) { group.Name = item.Name; group.Text = item.Text; if (item.ShowImage == true) { if (item.IsLarge == true) { group.Glyph = ImageConvert.ConvertToImage(item.LargeImage); if (group.Glyph == null) { group.Glyph = ImageConvert.ConvertToImage(item.Image); } } else { group.Glyph = ImageConvert.ConvertToImage(item.Image); if (group.Glyph == null) { group.Glyph = ImageConvert.ConvertToImage(item.LargeImage); } } } else { group.Glyph = null; } group.Tag = item; }
protected ButtonBase() { var typeName = GetType().Name; Name = "Autodesk:PowerTools:" + typeName; try { var standardIcon = ImageConvert.FromIconToIPictureDisp( icon: new Icon(typeof(ButtonBase), typeName + ".ico") ); _buttonDefinition = AddIn.Inventor.CommandManager.ControlDefinitions.AddButtonDefinition( DisplayName: DisplayName, InternalName: Name, Classification: CommandType, ClientId: AddIn.ClientId, DescriptionText: Description, ToolTipText: ToolTip, StandardIcon: standardIcon, LargeIcon: standardIcon, ButtonDisplay: DisplayType ); _buttonDefinition.OnExecute += OnExecute; IsEnabled = false; } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
private async void bt_addFingerprint_Click(object sender, RoutedEventArgs e) { OpenFileDialog dlg = new OpenFileDialog { InitialDirectory = "c:\\Pictures", Filter = "Image files (*.jpg, *.jpeg, *.jpe, *.jfif, *.png) | *.jpg; *.jpeg; *.jpe; *.jfif; *.png", RestoreDirectory = true }; if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK) { string selectedFileName = dlg.FileName; BitmapImage bitmap = new BitmapImage(); bitmap.BeginInit(); bitmap.UriSource = new Uri(selectedFileName); bitmap.EndInit(); CreateImage(bitmap); if (_userEdit == null) { _UserfingerprintsImage.Add(new FingerprintModel() { FingerPrintImage = ImageConvert.ImageToByte(bitmap) }); } else { await _dataController.AddFingerprint(new FingerprintModel() { UserId = _userEdit.User.Id, FingerPrintImage = ImageConvert.ImageToByte(bitmap) }); } } }
public override bool BufToByteGray(int nID, byte[] _FrameBuffer, byte[] buf) { ImageConvert ToImageConverRTV24 = new ImageConvert(); bool result = ToImageConverRTV24.BGR_To_Y(_FrameBuffer, buf, (UInt32)CamDeviceList[nID].GetWidth(), (UInt32)CamDeviceList[nID].GetHeight()); return(result); }
public byte[] Rgb2Gray(Bitmap temp) { bool bRet = false; int nWidth = temp.Width; int nHeight = temp.Height; int nDeep = temp.PixelFormat == PixelFormat.Format8bppIndexed ? 1 : (temp.PixelFormat == PixelFormat.Format32bppRgb || temp.PixelFormat == PixelFormat.Format32bppArgb || temp.PixelFormat == PixelFormat.Format32bppPArgb) ? 4 : 3; byte[] byBuffer = new byte[(uint)nWidth * (uint)nHeight * nDeep]; byte[] byBufferY = new byte[(uint)nWidth * (uint)nHeight * 1]; if (temp.PixelFormat == PixelFormat.Format24bppRgb || temp.PixelFormat == PixelFormat.Format32bppRgb || temp.PixelFormat == PixelFormat.Format32bppArgb || temp.PixelFormat == PixelFormat.Format32bppPArgb ) { byBuffer = ImageChangeHelper.Instance.ConvertBitmapToByteArray(temp); ImageConvert ic = new ImageConvert(); ic.BGR_To_Y(byBuffer, byBufferY, (uint)nWidth, (uint)nHeight); } else { byBufferY = ImageChangeHelper.Instance.ConvertBitmapToByteArray(temp); } return(byBufferY); }
public void Motion2aMultipleCompare() { try { //images in memory when sent to the ByteWrapper image1 = ImageConvert.ReturnByteWrapper(@"F:\temp\analysis\640x480\test_0.jpg"); ByteWrapper image2 = ImageConvert.ReturnByteWrapper(@"F:\temp\analysis\640x480\test_1.jpg"); PixelMatrix dummy = new PixelMatrix(); dummy.LinkCompare = true; dummy.Populate(new BitmapWrapper(ImageConvert.ReturnBitmap(image1.bytes)), new BitmapWrapper(ImageConvert.ReturnBitmap(image2.bytes))); MotionSensor_2a motion = new MotionSensor_2a(); motion.ThresholdSet = true; motion.settings.linkCompare = true; motion.Comparison = dummy.Comparision; motion.ImageCreated(image1, EventArgs.Empty); motion.ImageCreated(image2, EventArgs.Empty); motion.ImageCreated(image1, EventArgs.Empty); motion.ImageCreated(image2, EventArgs.Empty); Assert.IsTrue(true); } catch { Assert.IsTrue(false); } }
// This is a sample that moves in a random direction public static void Execute(AgentHost agentHost, ListBox lstMessage, Panel pnl3x3, Panel pnlDiagData, PictureBox pictureBoxMineCraft, CheckBox chkFullDebug) { WorldState worldState; Random rand = new Random(); // main loop: do { // Get Worldstate worldState = agentHost.getWorldState(); agentHost.sendCommand("move 1"); agentHost.sendCommand(string.Format("turn {0}", rand.NextDouble())); Thread.Sleep(500); // Log Mission Observation objObservation = RunMission.LogMission(worldState, lstMessage, pnl3x3, pnlDiagData, chkFullDebug); if (worldState.is_mission_running && worldState.video_frames.Count > 0) { // Converts the Malmo ByteVector to a Bitmap and display in pictureBoxMineCraft pictureBoxMineCraft.Image = ImageConvert.GetImageFromByteArray(worldState.video_frames[0].pixels); pictureBoxMineCraft.Invalidate(); pictureBoxMineCraft.Refresh(); } }while (worldState.is_mission_running); lstMessage.Items.Insert(0, "Mission has stopped."); }
public void TestValidator() { ByteWrapper image1 = ImageConvert.ReturnByteWrapper(@"F:\temp\analysis\640x480\test_0.jpg"); ImageValidator validator = new ImageValidator(); try { List <int> dimensions = ReturnDimensions(); Stopwatch sw = new Stopwatch(); using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"f:\temp\runtime\validator_analysis.txt", true)) { for (int i = 0; i < 10; i++) { sw.Restart(); validator.FileCreated(image1, EventArgs.Empty); sw.Stop(); file.WriteLine(sw.Elapsed.TotalMilliseconds); } } Assert.IsTrue(true); } catch { Assert.IsTrue(false); } }
/// <summary> /// foamliu, 2009/02/02, 彩色图片缩放. /// </summary> /// <param name="bmp"></param> /// <param name="sr"></param> /// <param name="sc"></param> /// <returns></returns> public static Bitmap Scale(Bitmap bmp, double sr, double sc) { int width, height; int[][][] img, newImg; Bitmap newBmp; ImageConvert.Bitmap2MatColor(bmp, out img, out width, out height); int newW = (int)(width * sc); int newH = (int)(height * sr); newImg = Util.BuildMatIntColor(newW, newH); for (int y = 0; y < newH; y++) { for (int x = 0; x < newW; x++) { double[] input = new double[] { y, x, 1 }; double[] output = NcvMatrix.ScaleInvert(input, sr, sc); int oldY = (int)Math.Round(output[0]); int oldX = (int)Math.Round(output[1]); if (Util.InRect(oldX, oldY, width, height)) { // RGB newImg[0][x][y] = img[0][oldX][oldY]; newImg[1][x][y] = img[1][oldX][oldY]; newImg[2][x][y] = img[2][oldX][oldY]; } } } ImageConvert.Mat2BitmapColor(newImg, newW, newH, out newBmp); return newBmp; }
/// <summary> /// foamliu, 2009/02/02, 彩色图片平移. /// </summary> /// <param name="bmp"></param> /// <param name="tr"></param> /// <param name="tc"></param> /// <returns></returns> public static Bitmap Translate(Bitmap bmp, double tr, double tc) { int width, height; int[][][] img, newImg; Bitmap newBmp; ImageConvert.Bitmap2MatColor(bmp, out img, out width, out height); newImg = Util.BuildMatIntColor(width, height); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { double[] input = new double[] { y, x, 1 }; double[] output = NcvMatrix.TranslateInvert(input, tr, tc); int oldY = (int)Math.Round(output[0]); int oldX = (int)Math.Round(output[1]); if (Util.InRect(oldX, oldY, width, height)) { // RGB newImg[0][x][y] = img[0][oldX][oldY]; newImg[1][x][y] = img[1][oldX][oldY]; newImg[2][x][y] = img[2][oldX][oldY]; } } } ImageConvert.Mat2BitmapColor(newImg, width, height, out newBmp); return newBmp; }
private async void LoadPerfil() { try { DependencyService.Get <IProgressDialog>().ProgressDialogShow(); Perfil = new PerfilModel(); var db = new DbContext(); var user = db.GetUsuario(); ServiceClient client = new ServiceClient(); var response = await client.GetListAllWithParam <PerfilModel>(Configuration.BaseUrl, $"pnl/api/get_socioApp?client={user.Client}&socio={user.DNI}"); DependencyService.Get <IProgressDialog>().ProgressDialogHide(); if (response != null) { Perfil = response; Perfil.PhotoConvert = ImageConvert.ConvertToBase(response.Photo); Perfil.Domicilio = response.Domicilio + " " + response.Numeracion; Perfil.Telefono = response.CaractTelefono + " " + response.Telefono; Perfil.Celular = response.CaractCelular + " " + response.Celular; } else { App.MessageError("Usuario no encontrado"); } } catch (Exception ex) { Debug.WriteLine(ex.Message); } }
private async Task MarkupImage(int frameIndex, RawFrame frame, IEnumerable <SSDProcessor.BoundingBox> boxes, CancellationToken ct) { var converter = new ImageConvert(); using var decoded = converter.Convert(frame, frame.Width, frame.Height, FFmpeg.AutoGen.AVPixelFormat.AV_PIX_FMT_BGR24); using var bitmap = GetBitmap(decoded); await _markup.MarkupImage(frameIndex, bitmap, boxes, ct); }
private void SendTestPattern() { try { unsafe { Bitmap testPattern = new Bitmap("wizard.jpeg"); SIPSorceryMedia.VPXEncoder vpxEncoder = new VPXEncoder(); vpxEncoder.InitEncoder(Convert.ToUInt32(testPattern.Width), Convert.ToUInt32(testPattern.Height)); SIPSorceryMedia.ImageConvert colorConverter = new ImageConvert(); byte[] sampleBuffer = null; byte[] encodedBuffer = new byte[4096]; while (!_exit) { if (_webRtcSessions.Any(x => x.Value.Peer.IsDtlsNegotiationComplete == true && x.Value.Peer.IsClosed == false)) { var stampedTestPattern = testPattern.Clone() as System.Drawing.Image; AddTimeStampAndLocation(stampedTestPattern, DateTime.UtcNow.ToString("dd MMM yyyy HH:mm:ss:fff"), "Test Pattern"); sampleBuffer = BitmapToRGB24(stampedTestPattern as System.Drawing.Bitmap); fixed (byte* p = sampleBuffer) { byte[] convertedFrame = null; colorConverter.ConvertRGBtoYUV(p, VideoSubTypesEnum.RGB24, testPattern.Width, testPattern.Height, VideoSubTypesEnum.I420, ref convertedFrame); fixed (byte* q = convertedFrame) { int encodeResult = vpxEncoder.Encode(q, sampleBuffer.Length, 1, ref encodedBuffer); if (encodeResult != 0) { logger.Warn("VPX encode of video sample failed."); continue; } } } stampedTestPattern.Dispose(); stampedTestPattern = null; lock (_webRtcSessions) { foreach (var session in _webRtcSessions.Where(x => x.Value.Peer.IsDtlsNegotiationComplete == true && x.Value.Peer.LocalIceCandidates.Any(y => y.RemoteRtpEndPoint != null))) { session.Value.Send(encodedBuffer); } } encodedBuffer = null; } Thread.Sleep(100); } } } catch (Exception excp) { logger.Error("Exception SendTestPattern. " + excp); } }
private static void SendRTPFromCamera() { try { unsafe { SIPSorceryMedia.MFVideoSampler videoSampler = new SIPSorceryMedia.MFVideoSampler(); //List<VideoMode> webcamModes = new List<VideoMode>(); //int deviceCount = videoSampler.GetVideoDevices(ref webcamModes); //foreach (var videoMode in webcamModes) //{ // Console.WriteLine(videoMode.DeviceFriendlyName + " " + (videoMode.VideoSubTypeFriendlyName ?? videoMode.VideoSubType.ToString()) + " " + videoMode.Width + "x" + videoMode.Height + "."); //} videoSampler.Init(_webcamIndex, _webcamVideoSubType, _webcamWidth, _webcamHeight); SIPSorceryMedia.VPXEncoder vpxEncoder = new VPXEncoder(); vpxEncoder.InitEncoder(_webcamWidth, _webcamHeight); SIPSorceryMedia.ImageConvert colorConverter = new ImageConvert(); byte pictureID = 0x1; byte[] sampleBuffer = null; byte[] encodedBuffer = new byte[4096]; while (true) { if (_webRTCClients.Any(x => x.STUNExchangeComplete == true && x.IsDtlsNegotiationComplete == true)) { int result = videoSampler.GetSample(ref sampleBuffer); if (result != 0) { Console.WriteLine("Video sampler returned a null sample."); } else { //Console.WriteLine("Got managed sample " + sample.Buffer.Length + ", is key frame " + sample.IsKeyFrame + "."); fixed (byte* p = sampleBuffer) { byte[] convertedFrame = null; colorConverter.ConvertToI420(p, _webcamVideoSubType, Convert.ToInt32(_webcamWidth), Convert.ToInt32(_webcamHeight), ref convertedFrame); //int encodeResult = vpxEncoder.Encode(p, sampleBuffer.Length, 1, ref encodedBuffer); fixed (byte* q = convertedFrame) { int encodeResult = vpxEncoder.Encode(q, sampleBuffer.Length, 1, ref encodedBuffer); if (encodeResult != 0) { Console.WriteLine("VPX encode of video sample failed."); continue; } } } lock (_webRTCClients) { foreach (var client in _webRTCClients.Where(x => x.STUNExchangeComplete && x.IsDtlsNegotiationComplete == true)) { try { //if (client.LastRtcpSenderReportSentAt == DateTime.MinValue) //{ // logger.Debug("Sending RTCP report to " + client.SocketAddress + "."); // // Send RTCP report. // RTCPPacket rtcp = new RTCPPacket(client.SSRC, 0, 0, 0, 0); // byte[] rtcpBuffer = rtcp.GetBytes(); // _webRTCReceiverClient.BeginSend(rtcpBuffer, rtcpBuffer.Length, client.SocketAddress, null, null); // //int rtperr = client.SrtpContext.ProtectRTP(rtcpBuffer, rtcpBuffer.Length - SRTP_AUTH_KEY_LENGTH); //} //Console.WriteLine("Sending VP8 frame of " + encodedBuffer.Length + " bytes to " + client.SocketAddress + "."); client.LastTimestamp = (client.LastTimestamp == 0) ? RTSPSession.DateTimeToNptTimestamp32(DateTime.Now) : client.LastTimestamp + TIMESTAMP_SPACING; for (int index = 0; index * RTP_MAX_PAYLOAD < encodedBuffer.Length; index++) { int offset = (index == 0) ? 0 : (index * RTP_MAX_PAYLOAD); int payloadLength = (offset + RTP_MAX_PAYLOAD < encodedBuffer.Length) ? RTP_MAX_PAYLOAD : encodedBuffer.Length - offset; byte[] vp8HeaderBytes = (index == 0) ? new byte[] { 0x10 } : new byte[] { 0x00 }; RTPPacket rtpPacket = new RTPPacket(payloadLength + SRTP_AUTH_KEY_LENGTH + vp8HeaderBytes.Length); rtpPacket.Header.SyncSource = client.SSRC; rtpPacket.Header.SequenceNumber = client.SequenceNumber++; rtpPacket.Header.Timestamp = client.LastTimestamp; rtpPacket.Header.MarkerBit = ((offset + payloadLength) >= encodedBuffer.Length) ? 1 : 0; // Set marker bit for the last packet in the frame. rtpPacket.Header.PayloadType = PAYLOAD_TYPE_ID; Buffer.BlockCopy(vp8HeaderBytes, 0, rtpPacket.Payload, 0, vp8HeaderBytes.Length); Buffer.BlockCopy(encodedBuffer, offset, rtpPacket.Payload, vp8HeaderBytes.Length, payloadLength); var rtpBuffer = rtpPacket.GetBytes(); //_webRTCReceiverClient.Send(rtpBuffer, rtpBuffer.Length, _wiresharpEP); int rtperr = client.SrtpContext.ProtectRTP(rtpBuffer, rtpBuffer.Length - SRTP_AUTH_KEY_LENGTH); if (rtperr != 0) { logger.Warn("SRTP packet protection failed, result " + rtperr + "."); } else { //logger.Debug("Sending RTP, offset " + offset + ", frame bytes " + payloadLength + ", vp8 header bytes " + vp8HeaderBytes.Length + ", timestamp " + rtpPacket.Header.Timestamp + ", seq # " + rtpPacket.Header.SequenceNumber + " to " + client.SocketAddress + "."); //_webRTCReceiverClient.Send(rtpBuffer, rtpBuffer.Length, client.SocketAddress); _webRTCReceiverClient.BeginSend(rtpBuffer, rtpBuffer.Length, client.SocketAddress, null, null); } } } catch (Exception sendExcp) { logger.Error("SendRTP exception sending to " + client.SocketAddress + ". " + sendExcp.Message); } } } pictureID++; if (pictureID > 127) { pictureID = 1; } encodedBuffer = null; sampleBuffer = null; } } } } } catch (Exception excp) { Console.WriteLine("Exception SendRTP. " + excp); } }