private void calibrateButton_Click(object sender, RoutedEventArgs e) { Bitmap bmp = BitmapFromSource((BitmapSource)normalVideoImage.Source); BitmapData bitmapData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, bmp.PixelFormat); var filter = new Crop(new Rectangle((bmp.Width / 2) - (FilterWidth / 4), (bmp.Height / 2) - (FilterHeight / 4), FilterWidth / 2, FilterHeight / 2)); var croppedBitmap = filter.Apply(bitmapData); var stats = new ImageStatistics(croppedBitmap); redTextBox.Text = Convert.ToInt32(stats.Red.Median).ToString(); greenTextBox.Text = Convert.ToInt32(stats.Green.Median).ToString(); blueTextBox.Text = Convert.ToInt32(stats.Blue.Median).ToString(); var brushColor = new System.Windows.Media.Color(); brushColor.R = byte.Parse(redTextBox.Text); brushColor.G = byte.Parse(greenTextBox.Text); brushColor.B = byte.Parse(blueTextBox.Text); brushColor.A = byte.MaxValue; calibratedColorRect.Fill = new SolidColorBrush(brushColor); calibrated = true; testPassedLabel.Content = ""; Corners.Clear(); StartDetecting = false; }
private void GenerateImageHistograms(System.Drawing.Bitmap bitmap) { if (bitmap == null) { return; } try { // Luminance ImageStatisticsHSL hslStatistics = new ImageStatisticsHSL(bitmap); polygonLuminanceHistogramPoints.Points = ConvertToPointCollection(hslStatistics.Luminance.Values); // RGB ImageStatistics rgbStatistics = new ImageStatistics(bitmap); polygonRedColorHistogramPoints.Points = ConvertToPointCollection(rgbStatistics.Red.Values); polygonGreenColorHistogramPoints.Points = ConvertToPointCollection(rgbStatistics.Green.Values); polygonBlueColorHistogramPoints.Points = ConvertToPointCollection(rgbStatistics.Blue.Values); //bmp.Dispose(); } catch { // ignored } }
private void GetAdditionalData(object o) { BitmapFile file = o as BitmapFile; try { if (!file.FileItem.IsRaw) { using (Bitmap bmp = new Bitmap(file.FileItem.FileName)) { // Luminance ImageStatisticsHSL hslStatistics = new ImageStatisticsHSL(bmp); file.LuminanceHistogramPoints = ConvertToPointCollection(hslStatistics.Luminance.Values); // RGB ImageStatistics rgbStatistics = new ImageStatistics(bmp); file.RedColorHistogramPoints = ConvertToPointCollection(rgbStatistics.Red.Values); file.GreenColorHistogramPoints = ConvertToPointCollection(rgbStatistics.Green.Values); file.BlueColorHistogramPoints = ConvertToPointCollection(rgbStatistics.Blue.Values); } } } catch (Exception ex) { Log.Error(ex); } }
/// <summary> /// Detects if a bitmap image of shred is empty by taking image statistics of it /// Empirical observation has shown that 80 is an adequate conservative threshold /// </summary> /// <param name="bmp">Bitmap of Shred</param> /// <returns></returns> public static bool IsEmpty(Bitmap bmp) { int threshold = 80; //threshold for number of zeroes in the histogram or number of missing grayscale values ImageStatistics rgbStatistics = new ImageStatistics(bmp); int[] redValues = rgbStatistics.Red.Values; int[] greenValues = rgbStatistics.Green.Values; int[] blueValues = rgbStatistics.Blue.Values; int zeroTally = 0; for (int i = 0; i < 256; i++) { int value = (redValues[i] + greenValues[i] + blueValues[i]) / 3; if (value == 0) { zeroTally++; } } bool output = zeroTally > threshold; return(output); }
public KNN(Blob blob) { img = new ImageStatistics(blob.Image); intensity = ((double)img.PixelsCountWithoutBlack / (double)img.PixelsCount) * 100; size = blob.Area; position = blob.Rectangle.Location; }
public override AlgorithmResult ProcessData() { byte[,] pixels = Input.Image.GetPixels(); if (gMin == -1 || gMean == -1 || gMax == -1) { var stats = new ImageStatistics(Input.Image); gMin = stats.Gray.Min; gMax = stats.Gray.Max; gMean = (byte)((gMax - gMin) / 2 + gMin); } InferenceSystem system = SetupInferenceSystem((byte)gMin, (byte)gMax, (byte)gMean); var result = new byte[pixels.GetLength(0), pixels.GetLength(1)]; for (int i = 0; i < pixels.GetLength(0); i++) { for (int j = 0; j < pixels.GetLength(1); j++) { system.SetInput("LumaIn", pixels[i, j]); double inferrenceResult = system.Evaluate("LumaOut"); result[i, j] = (byte)inferrenceResult; } } return(new AlgorithmResult(result)); }
protected virtual void FilterApplied(IplImage image) { try { if (previewImage.ptr == IntPtr.Zero) { previewImage = cvlib.CvCreateImage(cvlib.CvGetSize(ref image), (int)cvlib.IPL_DEPTH_8U, 3); } cvlib.CvCvtColor(ref image, ref previewImage, cvlib.CV_GRAY2BGR); Bitmap bitmap = cvlib.ToBitmap(previewImage, false); Bitmap grayscale = grayscaleFilter.Apply(bitmap); bitmap.Dispose(); ImageStatistics imageStatistics = new ImageStatistics(grayscale); Histogram grayHistogram = imageStatistics.GrayWithoutBlack; synchronizationContext.Send(state => { UpdatePictureBox(grayscale); histogram.Values = imageStatistics.Gray.Values; propertyGrid1.SelectedObject = grayHistogram; }, null); } catch (Exception e) { Trace.TraceInformation(e.Message); } }
private void RedrawCharts() { var hslStatistics = new ImageStatisticsHSL(image); var luminanceValues = hslStatistics.Luminance.Values; var rgbStatistics = new ImageStatistics(image); var redValues = rgbStatistics.Red.Values; var greenValues = rgbStatistics.Green.Values; var blueValues = rgbStatistics.Blue.Values; luminanceChart.Series["Series1"].Points.Clear(); redChart.Series["Series1"].Points.Clear(); greenChart.Series["Series1"].Points.Clear(); blueChart.Series["Series1"].Points.Clear(); for (var i = 1; i < luminanceValues.Length; ++i) { luminanceChart.Series["Series1"].Points.AddY(luminanceValues[i]); } for (var i = 1; i < redValues.Length; ++i) { redChart.Series["Series1"].Points.AddY(redValues[i]); } for (var i = 1; i < greenValues.Length; ++i) { greenChart.Series["Series1"].Points.AddY(greenValues[i]); } for (var i = 1; i < blueValues.Length; ++i) { blueChart.Series["Series1"].Points.AddY(blueValues[i]); } }
public void DrawLevelGraph() { try { if (ImagePath != null && ImagePath != "") { using (Bitmap bmp = new Bitmap(ImagePath)) { ImageStatisticsHSL hslStatistics = new ImageStatisticsHSL(bmp); L = ConvertToPointCollection(hslStatistics.Luminance.Values); ImageStatistics statistics = new ImageStatistics(bmp); R = ConvertToPointCollection(statistics.Red.Values); G = ConvertToPointCollection(statistics.Green.Values); B = ConvertToPointCollection(statistics.Blue.Values); } } else { L = null; R = null; G = null; B = null; } } catch (Exception) { } }
private void Form1_Load(object sender, EventArgs e) { Bitmap src = Bitmap.FromFile(@"C:\Users\phil\Pictures\vlcsnap-2017-10-01-21h39m20s991.png") as Bitmap; var stats = new ImageStatistics(src); histogram1.Color = Color.FromArgb(60, Color.Red); histogram1.Values = stats.Red.Values;; //typeof(ImageStatistics).GetMembers().Where(x => x.MemberType == typeof(Histogram)) //foreach (var ch in new[] //{ // (Red, stats.Red), // (Blue, stats.Blue), // (Green, stats.Green), // (Green, stats.), //}) var c = new Histogram(); c.Location = histogram1.Location; c.Size = histogram1.Size; c.Color = Color.FromArgb(60, Color.Red); c.Values = stats.Red.Values; }
public static int countNonBlackPixels(Bitmap img) { Bitmap formatIMG = convert(img, PixelFormat.Format32bppArgb); ImageStatistics stats = new ImageStatistics(formatIMG); return(stats.PixelsCountWithoutBlack); }
private void ComputeDetectorData(FitsImage Central, ImageStatistics CentralStats, StarData StarList, out MaskByMedian.MaskProperties MaskProp, out DotDetector SlowDetector, out LongTrailDetector.LongTrailData LTD) { MaskProp = new MaskByMedian.MaskProperties() { LTM = MaskThreshold.Low, UTM = MaskThreshold.High, ExtraMaskRadius = ExtraMaskRadius, MaskRadiusMultiplier = MaskRadiusMultiplier, StarList = StarList }; MaskByMedian.CreateMasker(Central, MaskProp, CentralStats); SlowDetector = new DotDetector() { HighThresholdMultiplier = DotDetectorThreshold.High, LowThresholdMultiplier = DotDetectorThreshold.Low, MinPix = DotMinPix, NonrepresentativeThreshold = NonrepresentativeThreshold }; LTD = LongTrailDetector.GeneralAlgorithmSetup( PSFSize: PSFDiameter, RLHTThreshold: RLHTThreshold, SegmentSelectThreshold: SegmentThreshold.High, SegmentDropThreshold: SegmentThreshold.Low, MaxInterblobDistance: MaxInterblobDistance, SimpleLine: true); LTD.DropCrowdedRegion = true; }
private void CorrectLevels() { ImageStatistics ims = new ImageStatistics(_recogimg); Histogram gr = ims.Gray; double median = gr.Median; double mean = gr.Mean; double stdev = gr.StdDev; //30 170 10 //for (int i = 30; i < 170; i += 10) //{ // this.CorrectLevel(i, (int)mean); // ims = new ImageStatistics(_recogimg); // gr = ims.Gray; // stdev = gr.StdDev; // mean = gr.Mean; // if (stdev >= 65 & mean >= 220) { break; } //} BradleyLocalThresholding filter = new BradleyLocalThresholding(); // apply the filter filter.ApplyInPlace(_recogimg); }
// Gather image statistics public void GatherStatistics(Bitmap image) { // avoid calculation in the case of the same image if (image != null) { if (currentImageHash == image.GetHashCode()) { return; } currentImageHash = image.GetHashCode(); } if (image != null) { System.Diagnostics.Debug.WriteLine("=== Gathering hostogram"); } // busy Capture = true; Cursor = Cursors.WaitCursor; // get statistics stat = (image == null) ? null : new ImageStatistics(image); // free Cursor = Cursors.Arrow; Capture = false; // clean combo channelCombo.Items.Clear(); channelCombo.Enabled = false; if (stat != null) { if (!stat.IsGrayscale) { // RGB picture channelCombo.Items.AddRange(new object[] { "Red", "Green", "Blue" }); channelCombo.Enabled = true; } else { // grayscale picture channelCombo.Items.Add("Gray"); } channelCombo.SelectedIndex = 0; } else { histogram.Values = null; meanLabel.Text = String.Empty; stdDevLabel.Text = String.Empty; medianLabel.Text = String.Empty; minLabel.Text = String.Empty; maxLabel.Text = String.Empty; levelLabel.Text = String.Empty; countLabel.Text = String.Empty; percentileLabel.Text = String.Empty; } }
void ShowPreview(IplImage image) { if (previewImage.ptr == IntPtr.Zero) { previewImage = cvlib.CvCreateImage(cvlib.CvGetSize(ref image), (int)cvlib.IPL_DEPTH_8U, 3); } cvlib.CvCvtColor(ref image, ref previewImage, cvlib.CV_GRAY2BGR); Bitmap bitmap = cvlib.ToBitmap(previewImage, false); Bitmap grayscale = grayscaleFilter.Apply(bitmap); ImageStatistics imageStatistics = new ImageStatistics(grayscale); Histogram grayHistogram = imageStatistics.GrayWithoutBlack; PaintBlobs(bitmap); synchronizationContext.Send(state => { UpdatePictureBox(bitmap); histogram.Values = imageStatistics.Gray.Values; propertyGrid1.SelectedObject = grayHistogram; }, null); bitmap.Dispose(); }
private static Bitmap CreateGrayscale(Bitmap image) { const int size = 512; float scale = Math.Min(size / (float)image.Width, size / (float)image.Height); ResizeBicubic resize = new ResizeBicubic((int)(image.Width*scale), (int)(image.Height*scale)); ImageStatistics stat = new ImageStatistics( image ); LevelsLinear levelsLinear = new LevelsLinear { Output = new IntRange(0, 255), InRed = stat.Red.GetRange(.95), InBlue = stat.Blue.GetRange(.95), InGreen = stat.Green.GetRange(.95) }; SaturationCorrection sc = new SaturationCorrection(-1); Bitmap square = new Bitmap(size, size); using(Bitmap resized = resize.Apply(sc.Apply(levelsLinear.Apply(image)).MakeGrayscale())) using (Graphics g = Graphics.FromImage(square)) { g.DrawImage(resized, new Point((size-resized.Width) / 2 ,0)); } return square; }
public void Calculate(Bitmap b) { ImageStatistics rgbStatistics = new ImageStatistics(b); redValues = rgbStatistics.Red.Values; greenValues = rgbStatistics.Green.Values; blueValues = rgbStatistics.Blue.Values; }
private void GetStatistics() { //ImageStatistics statistics = new ImageStatistics(_mconvgrayimg); //statistics. //Histogram grayhisto = statistics.Gray; //GetOrginalImgMaxValue = grayhisto.Max; //OnPropertyChanged("GetOrginalImgMaxValue"); //GetOrginalImgMinValue = grayhisto.Min; //OnPropertyChanged("GetOrginalImgMinValue"); //GetOrginalImgMedianValue = grayhisto.Median; //OnPropertyChanged("GetOrginalImgMedianValue"); //GetOrginalImgStdDevValue = grayhisto.StdDev; //OnPropertyChanged("GetOrginalImgStdDevValue"); //GetOrginalImgMeanValue = grayhisto.Mean; //OnPropertyChanged("GetOrginalImgMeanValue"); // ImageStatisticsHSL statistics = new ImageStatisticsHSL(_medgeimg); // ContinuousHistogram hist = statistics.LuminanceWithoutBlack; ImageStatistics statistics = new ImageStatistics(_medgeimg); Histogram hist = statistics.Gray; GetOrginalImgMaxValue = hist.Max; OnPropertyChanged("GetOrginalImgMaxValue"); GetOrginalImgMinValue = hist.Min; OnPropertyChanged("GetOrginalImgMinValue"); GetOrginalImgMedianValue = hist.Median; OnPropertyChanged("GetOrginalImgMedianValue"); GetOrginalImgStdDevValue = (float)hist.StdDev; OnPropertyChanged("GetOrginalImgStdDevValue"); GetOrginalImgMeanValue = (float)hist.Mean; OnPropertyChanged("GetOrginalImgMeanValue"); //ImageStatisticsHSL statistics1 = new ImageStatisticsHSL(_mimg); //ContinuousHistogram hist1 = statistics1.Luminance; ImageStatistics statistics1 = new ImageStatistics(_medgeimg); Histogram hist1 = statistics.Gray; GetOrginalImgMaxValue1 = hist1.Max; OnPropertyChanged("GetOrginalImgMaxValue1"); GetOrginalImgMinValue1 = hist1.Min; OnPropertyChanged("GetOrginalImgMinValue1"); GetOrginalImgMedianValue1 = hist1.Median; OnPropertyChanged("GetOrginalImgMedianValue1"); GetOrginalImgStdDevValue1 = (float)hist1.StdDev; OnPropertyChanged("GetOrginalImgStdDevValue1"); GetOrginalImgMeanValue1 = (float)hist1.Mean; OnPropertyChanged("GetOrginalImgMeanValue1"); }
public static double EvaluateM(UnmanagedImage image) { byte[,] pixels = image.GetPixels(); var stats = new ImageStatistics(image); var minGrayLevel = (byte)stats.Gray.Min; var maxGrayLevel = (byte)stats.Gray.Max; return((double)(maxGrayLevel - minGrayLevel) / (double)(maxGrayLevel + minGrayLevel)); }
private double Fitness(MyRectangle rect, byte intensity) { Crop crop = new Crop(rect.Rectangle); var cropped = crop.Apply(GreyImage); ImageStatistics stat = new ImageStatistics(crop.Apply(GreyImage)); Histogram hist = stat.Gray; double sameColorRatio = (double)hist.Values[intensity] / hist.TotalCount; return(sameColorRatio == 1 ? -rect.Size : -sameColorRatio); }
public static Bitmap Equalize(Bitmap image, Rectangle region) { int startX = region.Left; int startY = region.Top; int stopX = image.Width - 1; int stopY = image.Height - 1; if (startX + region.Width < image.Width) { stopX = startX + region.Width; } if (startY + region.Height < image.Height) { stopY = startX + region.Height; } int numberOfPixels = (stopX - startX) * (stopY - startY); Bitmap bitmap = new Bitmap(region.Width, region.Height); Graphics g = Graphics.FromImage(bitmap); g.DrawImage(image, new Rectangle(0, 0, region.Width, region.Height), region, GraphicsUnit.Pixel); ImageStatistics rgbStatistics = new ImageStatistics(bitmap); byte[] equalizedHistogramR = EqualizeHistogram(rgbStatistics.Red.Values, numberOfPixels); byte[] equalizedHistogramG = EqualizeHistogram(rgbStatistics.Green.Values, numberOfPixels); byte[] equalizedHistogramB = EqualizeHistogram(rgbStatistics.Blue.Values, numberOfPixels); var b = new Bitmap(image); BitmapData bmpData = b.LockBits(new Rectangle(0, 0, b.Width, b.Height), ImageLockMode.ReadWrite, b.PixelFormat); IntPtr ptr = bmpData.Scan0; int stride = bmpData.Stride; int bytes = Math.Abs(bmpData.Stride) * b.Height; byte[] rgbValues = new byte[bytes]; System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes); Parallel.For(startY, stopY, y => { for (int x = startX; x < stopX; x++) { int i = y * stride + x * 4; rgbValues[i] = equalizedHistogramR[rgbValues[i]]; rgbValues[i + 1] = equalizedHistogramG[rgbValues[i + 1]]; rgbValues[i + 2] = equalizedHistogramB[rgbValues[i + 2]]; } }); System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes); b.UnlockBits(bmpData); return(b); }
/* Given two images it makes a histogram comparison of its color channels * and returns a double indicating the level of similarity. * The smaller the value, the more similar the images are */ private double HistogramBitmapDifference(Bitmap image1, Bitmap image2) { ImageStatistics stats1 = new ImageStatistics(image1); ImageStatistics stats2 = new ImageStatistics(image2); double blueDiff = Math.Abs(stats1.Blue.Mean - stats2.Blue.Mean); double greenDiff = Math.Abs(stats1.Green.Mean - stats2.Green.Mean); double redDiff = Math.Abs(stats1.Red.Mean - stats2.Red.Mean); return((redDiff + blueDiff + greenDiff) / 3.0d); }
private void GetHistogram() { ImageStatistics rgbStatistics = new ImageStatistics(_image); AForge.Math.Histogram h = rgbStatistics.Red; RedValues = h.Values; h = rgbStatistics.Green; GreenValues = h.Values; h = rgbStatistics.Blue; BlueValues = h.Values; }
private void ProcessSingleImage(Bitmap source) { ImageStatistics stats = new ImageStatistics(source); LevelsLinear levelsLinear = new LevelsLinear { InRed = stats.Red.GetRange(0.87), InGreen = stats.Green.GetRange(0.87), InBlue = stats.Blue.GetRange(0.87) }; levelsLinear.ApplyInPlace(source); }
public bool isImageEmpty(Bitmap src) { bool ret = false; Bitmap g = Grayscale.CommonAlgorithms.BT709.Apply(src); ImageStatistics stat = new ImageStatistics(g); double[][] ds = { new double[] { stat.Gray.Mean, stat.Gray.Median, stat.Gray.StdDev } }; Program.logIt(string.Format("{0},{1},{2}", ds[0][0], ds[0][1], ds[0][2])); bool[] res = svm.Decide(ds); ret = !res[0]; return(ret); }
public TumorStat(Bitmap mytumor) { InitializeComponent(); tumorimage = mytumor; ImageStatistics st = new ImageStatistics(mytumor); for (int i = 0; i < st.Gray.Values.Length; i++) { DataPoint dt = new DataPoint(i, st.Gray.Values[i]); chart.Series[0].Points.Add(dt); } }
public override void calculate() { base.convertToGrayPicture(); ImageStatistics stat = new ImageStatistics(this.image); Histogram CalstatGary = stat.Gray; int median = CalstatGary.Median; double mean = CalstatGary.Mean; double sd = CalstatGary.StdDev; int drak = median - (int)sd / 2; base.calculate(); }
/* Given two images it makes a histogram comparison of its color channels * and returns a double indicating the level of similarity. * The smaller the value, the more similar the images are */ private double HistogramBitmapDifference(Bitmap image1, Bitmap image2) { ImageStatistics stats1 = new ImageStatistics(image1); ImageStatistics stats2 = new ImageStatistics(image2); double blueDiff = Math.Abs(stats1.Blue.Mean - stats2.Blue.Mean); double greenDiff = Math.Abs(stats1.Green.Mean - stats2.Green.Mean); double redDiff = Math.Abs(stats1.Red.Mean - stats2.Red.Mean); //Globals.Director.WriteDebug(WRITE_DEBUG,"\t --- Rd: " + redDiff + " Gd: " + greenDiff + " Bd: " + blueDiff); return((redDiff + blueDiff + greenDiff) / 3.0d); }
/*[Category("3: Blue Dengan black")] * public int BlueMedian * { * get { return statRGB.Blue.Median; } * }*/ /// <summary> /// CLASS MEMBANGUN NILAI RGB /// </summary> public ColorImageStatisticsDescription(Bitmap imagestat) { //membuat variabel dimensi gambar untuk waktu yg sebaik-baiknya int width = imagestat.Width; int height = imagestat.Height; //Bit kunci untuk sistem memori supaya pemrosesan cepat BitmapData imgData = imagestat.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); //Mengumpulkan statistik statRGB = new ImageStatistics(new UnmanagedImage(imgData)); // unlock image imagestat.UnlockBits(imgData); }
private static int ScanConstellations() { double yReference = 720.0; int constellation; if (Navigation.GetAspectRatio() == new Size(8, 5)) { yReference = 800.0; } Rectangle constActivate = new RECT( Left: (int)(70 / 1280.0 * Navigation.GetWidth()), Top: (int)(665 / 720.0 * Navigation.GetHeight()), Right: (int)(100 / 1280.0 * Navigation.GetWidth()), Bottom: (int)(695 / 720.0 * Navigation.GetHeight())); for (constellation = 0; constellation < 6; constellation++) { // Select Constellation int yOffset = (int)((180 + (constellation * 75)) / yReference * Navigation.GetHeight()); if (Navigation.GetAspectRatio() == new Size(8, 5)) { yOffset = (int)((225 + (constellation * 75)) / yReference * Navigation.GetHeight()); } Navigation.SetCursorPos(Navigation.GetPosition().Left + (int)(1130 / 1280.0 * Navigation.GetWidth()), Navigation.GetPosition().Top + yOffset); Navigation.Click(); Navigation.Speed speed = constellation == 0 ? Navigation.Speed.Normal : Navigation.Speed.Fast; Navigation.SystemRandomWait(speed); // Grab Color using (Bitmap region = Navigation.CaptureRegion(constActivate)) { // Check a small region next to the text "Activate" // for a mostly white backround ImageStatistics statistics = new ImageStatistics(region); if (statistics.Red.Mean >= 190 && statistics.Green.Mean >= 190 && statistics.Blue.Mean >= 190) { break; } } } Navigation.sim.Keyboard.KeyPress(WindowsInput.Native.VirtualKeyCode.ESCAPE); UserInterface.SetCharacter_Constellation(constellation); return(constellation); }
public static Bitmap Process(Bitmap image, Rectangle region) { int startX = region.Left; int startY = region.Top; int stopX = image.Width - 1; int stopY = image.Height - 1; if (startX + region.Width < image.Width) { stopX = startX + region.Width; } if (startY + region.Height < image.Height) { stopY = startX + region.Height; } int numberOfPixels = (stopX - startX) * (stopY - startY); Bitmap bitmap = new Bitmap(region.Width, region.Height); Graphics g = Graphics.FromImage(bitmap); g.DrawImage(image, new Rectangle(0, 0, region.Width, region.Height), region, GraphicsUnit.Pixel); ImageStatistics rgbStatistics = new ImageStatistics(bitmap); var b = new Bitmap(image); BitmapData bmpData = b.LockBits(new Rectangle(0, 0, b.Width, b.Height), ImageLockMode.ReadWrite, b.PixelFormat); IntPtr ptr = bmpData.Scan0; int stride = bmpData.Stride; int bytes = Math.Abs(bmpData.Stride) * b.Height; byte[] rgbValues = new byte[bytes]; System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes); Parallel.For(startY, stopY, y => { for (int x = startX; x < stopX; x++) { int i = y * stride + x * 4; //rgbValues[i] = curve[rgbValues[i]]; //rgbValues[i + 1] = curve[rgbValues[i + 1]]; //rgbValues[i + 2] = curve[rgbValues[i + 2]]; } }); System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes); b.UnlockBits(bmpData); return b; }
/// <summary> /// Process the filter on the specified image. /// </summary> /// /// <param name="image">Source image data.</param> /// protected override unsafe void ProcessFilter( UnmanagedImage image ) { UnmanagedImage bgImage = null; BitmapData bgLockedData = null; // get image size int width = image.Width; int height = image.Height; int offset = image.Stride - ( ( image.PixelFormat == PixelFormat.Format8bppIndexed ) ? width : width * 3 ); // check if we have provided background if ( ( backgroundImage == null ) && ( unmanagedBackgroundImage == null ) ) { // resize image to 1/3 of its original size to make bluring faster ResizeBicubic resizeFilter = new ResizeBicubic( (int) width / 3, (int) height / 3 ); UnmanagedImage tempImage = resizeFilter.Apply( image ); // create background image from the input image blurring it with Gaussian 5 times GaussianBlur blur = new GaussianBlur( 5, 21 ); blur.ApplyInPlace( tempImage ); blur.ApplyInPlace( tempImage ); blur.ApplyInPlace( tempImage ); blur.ApplyInPlace( tempImage ); blur.ApplyInPlace( tempImage ); // resize the blurred image back to original size resizeFilter.NewWidth = width; resizeFilter.NewHeight = height; bgImage = resizeFilter.Apply( tempImage ); tempImage.Dispose( ); } else { if ( backgroundImage != null ) { // check background image if ( ( width != backgroundImage.Width ) || ( height != backgroundImage.Height ) || ( image.PixelFormat != backgroundImage.PixelFormat ) ) { throw new InvalidImagePropertiesException( "Source image and background images must have the same size and pixel format" ); } // lock background image bgLockedData = backgroundImage.LockBits( new Rectangle( 0, 0, width, height ), ImageLockMode.ReadOnly, backgroundImage.PixelFormat ); bgImage = new UnmanagedImage( bgLockedData ); } else { bgImage = unmanagedBackgroundImage; } } // get background image's statistics (mean value is used as correction factor) ImageStatistics bgStatistics = new ImageStatistics( bgImage ); byte* src = (byte*) image.ImageData.ToPointer( ); byte* bg = (byte*) bgImage.ImageData.ToPointer( ); // do the job if ( image.PixelFormat == PixelFormat.Format8bppIndexed ) { // grayscale image double mean = bgStatistics.Gray.Mean; for ( int y = 0; y < height; y++ ) { for ( int x = 0; x < width; x++, src++, bg++ ) { if ( *bg != 0 ) { *src = (byte) Math.Min( mean * *src / *bg, 255 ); } } src += offset; bg += offset; } } else { // color image double meanR = bgStatistics.Red.Mean; double meanG = bgStatistics.Green.Mean; double meanB = bgStatistics.Blue.Mean; for ( int y = 0; y < height; y++ ) { for ( int x = 0; x < width; x++, src += 3, bg += 3 ) { // red if ( bg[RGB.R] != 0 ) { src[RGB.R] = (byte) Math.Min( meanR * src[RGB.R] / bg[RGB.R], 255 ); } // green if ( bg[RGB.G] != 0 ) { src[RGB.G] = (byte) Math.Min( meanG * src[RGB.G] / bg[RGB.G], 255 ); } // blue if ( bg[RGB.B] != 0 ) { src[RGB.B] = (byte) Math.Min( meanB * src[RGB.B] / bg[RGB.B], 255 ); } } src += offset; bg += offset; } } if ( backgroundImage != null ) { backgroundImage.UnlockBits( bgLockedData ); } // dispose background image if it was not set manually if ( ( backgroundImage == null ) && ( unmanagedBackgroundImage == null ) ) { bgImage.Dispose( ); } }