So i have added the coding4fun and microsoft sources and even done what is in the kinect sdk for displaying the kinect image frame on the screen, but for some reason it wont show, i works on the sdk though
Code I've Written
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Research.Kinect.Nui;
using Coding4Fun.Kinect.Wpf;
using System.Net.Mail;
using System.IO;
using System.ComponentModel;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
Runtime nui;
int PersonDetected = 0;
int totalFrames = 0;
int lastFrames = 0;
DateTime lastTime = DateTime.MaxValue;
Dictionary<JointID, Brush> jointColors = new Dictionary<JointID, Brush>() {
{JointID.HipCenter, new SolidColorBrush(Color.FromRgb(169, 176, 155))},
{JointID.Spine, new SolidColorBrush(Color.FromRgb(169, 176, 155))},
{JointID.ShoulderCenter, new SolidColorBrush(Color.FromRgb(168, 230, 29))},
{JointID.Head, new SolidColorBrush(Color.FromRgb(200, 0, 0))},
{JointID.ShoulderLeft, new SolidColorBrush(Color.FromRgb(79, 84, 33))},
{JointID.ElbowLeft, new SolidColorBrush(Color.FromRgb(84, 33, 42))},
{JointID.WristLeft, new SolidColorBrush(Color.FromRgb(255, 126, 0))},
{JointID.HandLeft, new SolidColorBrush(Color.FromRgb(215, 86, 0))},
{JointID.ShoulderRight, new SolidColorBrush(Color.FromRgb(33, 79, 84))},
{JointID.ElbowRight, new SolidColorBrush(Color.FromRgb(33, 33, 84))},
{JointID.WristRight, new SolidColorBrush(Color.FromRgb(77, 109, 243))},
{JointID.HandRight, new SolidColorBrush(Color.FromRgb(37, 69, 243))},
{JointID.HipLeft, new SolidColorBrush(Color.FromRgb(77, 109, 243))},
{JointID.KneeLeft, new SolidColorBrush(Color.FromRgb(69, 33, 84))},
{JointID.AnkleLeft, new SolidColorBrush(Color.FromRgb(229, 170, 122))},
{JointID.FootLeft, new SolidColorBrush(Color.FromRgb(255, 126, 0))},
{JointID.HipRight, new SolidColorBrush(Color.FromRgb(181, 165, 213))},
{JointID.KneeRight, new SolidColorBrush(Color.FromRgb(71, 222, 76))},
{JointID.AnkleRight, new SolidColorBrush(Color.FromRgb(245, 228, 156))},
{JointID.FootRight, new SolidColorBrush(Color.FromRgb(77, 109, 243))}
};
private void Window_Loaded(object sender, RoutedEventArgs e)
{
if (Runtime.Kinects.Count == 0)
{
MessageBox.Show("No Kinect Detected");
}
else
{
nui = Runtime.Kinects[0];
nui.Initialize(RuntimeOptions.UseColor | RuntimeOptions.UseSkeletalTracking);
lastTime = DateTime.Now;
nui.VideoFrameReady += new EventHandler<ImageFrameReadyEventArgs>(nui_VideoFrameReady);
nui.SkeletonFrameReady += new EventHandler<SkeletonFrameReadyEventArgs>(nui_SkeletonFrameReady);
//nui.DepthFrameReady += new EventHandler<ImageFrameReadyEventArgs>(nui_DepthFrameReady);
nui.VideoStream.Open(ImageStreamType.Video, 2, ImageResolution.Resolution640x480, ImageType.Color);
//nui.DepthStream.Open(ImageStreamType.Depth, 2, ImageResolution.Resolution640x480, ImageType.DepthAndPlayerIndex);
}
}
void nui_VideoFrameReady(object sender, ImageFrameReadyEventArgs e)
{
//KinectImage.Source = e.ImageFrame.ToBitmapSource();
PlanarImage Image = e.ImageFrame.Image;
++totalFrames;
{
string bb1 = Convert.ToString(DateTime.Now);
string filename = "C:\\Kinected\\Kinect1_Image " + bb1 + ".jpg";
KinectImage.Source = BitmapSource.Create(
Image.Width, Image.Height, 96, 96, PixelFormats.Bgr32, null, Image.Bits, Image.Width * Image.BytesPerPixel);
BitmapSource image = BitmapSource.Create(
Image.Width, Image.Height, 96, 96, PixelFormats.Bgr32, null, Image.Bits, Image.Width * Image.BytesPerPixel);
if (PersonDetected == 1)
{
image.Save(filename, Coding4Fun.Kinect.Wpf.ImageFormat.Jpeg);
SendNotificationEmail();
PersonDetected = 0;
}
}
}
Skeletal Sample Code
using System;
using System.Net.Mail;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Research.Kinect.Nui;
using Coding4Fun.Kinect.WinForm;
using Coding4Fun.Kinect.Wpf;
using System.IO;
using System.ComponentModel;
namespace SkeletalViewer
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
Runtime nui;
// public int ElevationAngle { get; set; }
// public static readonly int ElevationMaximum;
// public static readonly int ElevationMinimum;
//public static readonly int ElevationMedian;
//int ElevationMedian = ElevationAngle == 0;
int totalFrames = 0;
int totalFrames2 = 0;
int lastFrames = 0;
int PersonDetected = 0;
DateTime lastTime = DateTime.MaxValue;
// We want to control how depth data gets converted into false-color data
// for more intuitive visualization, so we keep 32-bit color frame buffer versions of
// these, to be updited whenever we receive and process a 16-bit frame.
const int RED_IDX = 2;
const int GREEN_IDX = 1;
const int BLUE_IDX = 0;
byte[] depthFrame32 = new byte[320 * 240 * 4];
Dictionary<JointID,Brush> jointColors = new Dictionary<JointID,Brush>() {
{JointID.HipCenter, new SolidColorBrush(Color.FromRgb(169, 176, 155))},
{JointID.Spine, new SolidColorBrush(Color.FromRgb(169, 176, 155))},
{JointID.ShoulderCenter, new SolidColorBrush(Color.FromRgb(168, 230, 29))},
{JointID.Head, new SolidColorBrush(Color.FromRgb(200, 0, 0))},
{JointID.ShoulderLeft, new SolidColorBrush(Color.FromRgb(79, 84, 33))},
{JointID.ElbowLeft, new SolidColorBrush(Color.FromRgb(84, 33, 42))},
{JointID.WristLeft, new SolidColorBrush(Color.FromRgb(255, 126, 0))},
{JointID.HandLeft, new SolidColorBrush(Color.FromRgb(215, 86, 0))},
{JointID.ShoulderRight, new SolidColorBrush(Color.FromRgb(33, 79, 84))},
{JointID.ElbowRight, new SolidColorBrush(Color.FromRgb(33, 33, 84))},
{JointID.WristRight, new SolidColorBrush(Color.FromRgb(77, 109, 243))},
{JointID.HandRight, new SolidColorBrush(Color.FromRgb(37, 69, 243))},
{JointID.HipLeft, new SolidColorBrush(Color.FromRgb(77, 109, 243))},
{JointID.KneeLeft, new SolidColorBrush(Color.FromRgb(69, 33, 84))},
{JointID.AnkleLeft, new SolidColorBrush(Color.FromRgb(229, 170, 122))},
{JointID.FootLeft, new SolidColorBrush(Color.FromRgb(255, 126, 0))},
{JointID.HipRight, new SolidColorBrush(Color.FromRgb(181, 165, 213))},
{JointID.KneeRight, new SolidColorBrush(Color.FromRgb(71, 222, 76))},
{JointID.AnkleRight, new SolidColorBrush(Color.FromRgb(245, 228, 156))},
{JointID.FootRight, new SolidColorBrush(Color.FromRgb(77, 109, 243))}
};
private void Window_Loaded(object sender, EventArgs e)
{
nui = new Runtime();
try
{
nui.Initialize(RuntimeOptions.UseDepthAndPlayerIndex | RuntimeOptions.UseSkeletalTracking | RuntimeOptions.UseColor);
}
catch (InvalidOperationException)
{
System.Windows.MessageBox.Show("Runtime initialization failed. Please make sure Kinect device is plugged in.");
return;
}
try
{
nui.VideoStream.Open(ImageStreamType.Video, 2, ImageResolution.Resolution640x480, ImageType.Color);
nui.DepthStream.Open(ImageStreamType.Depth, 2, ImageResolution.Resolution320x240, ImageType.DepthAndPlayerIndex);
}
catch (InvalidOperationException)
{
System.Windows.MessageBox.Show("Failed to open stream. Please make sure to specify a supported image type and resolution.");
return;
}
if (Runtime.Kinects.Count < 2)
{
lastTime = DateTime.Now;
nui.DepthFrameReady += new EventHandler<ImageFrameReadyEventArgs>(nui_DepthFrameReady);
nui.SkeletonFrameReady += new EventHandler<SkeletonFrameReadyEventArgs>(nui_SkeletonFrameReady);
nui.VideoFrameReady += new EventHandler<ImageFrameReadyEventArgs>(nui_ColorFrameReady2);
}
if (Runtime.Kinects.Count == 2)
{
lastTime = DateTime.Now;
nui.DepthFrameReady += new EventHandler<ImageFrameReadyEventArgs>(nui_DepthFrameReady);
nui.SkeletonFrameReady += new EventHandler<SkeletonFrameReadyEventArgs>(nui_SkeletonFrameReady);
nui.VideoFrameReady += new EventHandler<ImageFrameReadyEventArgs>(nui_ColorFrameReady2);
nui.VideoFrameReady += new EventHandler<ImageFrameReadyEventArgs>(nui_ColorFrameReady3);
}
}
// Converts a 16-bit grayscale depth frame which includes player indexes into a 32-bit frame
// that displays different players in different colors
byte[] convertDepthFrame(byte[] depthFrame16)
{
for (int i16 = 0, i32 = 0; i16 < depthFrame16.Length && i32 < depthFrame32.Length; i16 += 2, i32 += 4)
{
//
// System.Windows.MessageBox.Show(depthFrame16);
int player = depthFrame16[i16] & 0x07;
int realDepth = (depthFrame16[i16+1] << 5) | (depthFrame16[i16] >> 3);
// transform 13-bit depth information into an 8-bit intensity appropriate
// for display (we disregard information in most significant bit)
byte intensity = (byte)(255 - (255 * realDepth / 0x0fff));
depthFrame32[i32 + RED_IDX] = 0;
depthFrame32[i32 + GREEN_IDX] = 0;
depthFrame32[i32 + BLUE_IDX] = 0;
// choose different display colors based on player
switch (player)
{
case 0:
depthFrame32[i32 + RED_IDX] = (byte)(intensity / 2);
depthFrame32[i32 + GREEN_IDX] = (byte)(intensity / 2);
depthFrame32[i32 + BLUE_IDX] = (byte)(intensity / 2);
break;
case 1:
depthFrame32[i32 + RED_IDX] = intensity;
break;
case 2:
depthFrame32[i32 + GREEN_IDX] = intensity;
break;
case 3:
depthFrame32[i32 + RED_IDX] = (byte)(intensity / 4);
depthFrame32[i32 + GREEN_IDX] = (byte)(intensity);
depthFrame32[i32 + BLUE_IDX] = (byte)(intensity);
break;
case 4:
depthFrame32[i32 + RED_IDX] = (byte)(intensity);
depthFrame32[i32 + GREEN_IDX] = (byte)(intensity);
depthFrame32[i32 + BLUE_IDX] = (byte)(intensity / 4);
break;
case 5:
depthFrame32[i32 + RED_IDX] = (byte)(intensity);
depthFrame32[i32 + GREEN_IDX] = (byte)(intensity / 4);
depthFrame32[i32 + BLUE_IDX] = (byte)(intensity);
break;
case 6:
depthFrame32[i32 + RED_IDX] = (byte)(intensity / 2);
depthFrame32[i32 + GREEN_IDX] = (byte)(intensity / 2);
depthFrame32[i32 + BLUE_IDX] = (byte)(intensity);
break;
case 7:
depthFrame32[i32 + RED_IDX] = (byte)(255 - intensity);
depthFrame32[i32 + GREEN_IDX] = (byte)(255 - intensity);
depthFrame32[i32 + BLUE_IDX] = (byte)(255 - intensity);
break;
}
// file_dist.Close();
}
// Console.WriteLine(depthFrame32);
return depthFrame32;
}
void nui_ColorFrameReady(object sender, ImageFrameReadyEventArgs e)
{
// 32-bit per pixel, RGBA image
PlanarImage Image = e.ImageFrame.Image;
++totalFrames;
string bb1 = Convert.ToString(totalFrames);
// string file_name_3 = "C:\\Research\\Kinect\\Proposal\\Depth_Img" + bb1 + ".jpg"; xxx
string file_name_4 = "C:\\temp\\Video_Img" + bb1 + ".jpg";
video.Source = BitmapSource.Create(
Image.Width, Image.Height, 96, 96, PixelFormats.Bgr32, null, Image.Bits, Image.Width * Image.BytesPerPixel);
BitmapSource image4 = BitmapSource.Create(
Image.Width, Image.Height, 96, 96, PixelFormats.Bgr32, null, Image.Bits, Image.Width * Image.BytesPerPixel);
// image4.Save(file_name_4, Coding4Fun.Kinect.Wpf.ImageFormat.Jpeg);
}
void nui_ColorFrameReady2(object sender, ImageFrameReadyEventArgs e)
{
// 32-bit per pixel, RGBA image xxx
PlanarImage Image = e.ImageFrame.Image;
//int deltaFrames = totalFrames - lastFrameWithMotion;
//if (totalFrames2 <= stopFrameNumber & deltaFrames > 300)
{
++totalFrames2;
string bb1 = Convert.ToString(totalFrames2);
// string file_name_3 = "C:\\Research\\Kinect\\Proposal\\Depth_Img" + bb1 + ".jpg"; xxx
string file_name_4 = "C:\\Kinected\\Kinect1_Img" + bb1 + ".jpg";
video.Source = BitmapSource.Create(
Image.Width, Image.Height, 96, 96, PixelFormats.Bgr32, null, Image.Bits, Image.Width * Image.BytesPerPixel);
BitmapSource image4 = BitmapSource.Create(
Image.Width, Image.Height, 96, 96, PixelFormats.Bgr32, null, Image.Bits, Image.Width * Image.BytesPerPixel);
if (PersonDetected == 1)
{
if (totalFrames2 % 10 == 0)
{
image4.Save(file_name_4, Coding4Fun.Kinect.Wpf.ImageFormat.Jpeg);
SendNotificationEmail();
PersonDetected = 0;
// lastFrameWithMotion = totalFrames;
// topFrameNumber += 100;
}
}
}
}
Any ideas about why it isnt displaying the image on my application?
Do what benjgorman said, if your using an xbox kinect, it will still work with the new sdk. You can get it here. The code feels a bit different from the older programs, but you'll get used to it pretty fast. You can get the tutorials i used from here, or use the code i provided, make sure that you add the sources Microsoft.Kinect and add the project from the kinect explorer(you download that via the sdk) Microsoft.Samples.Kinect.WpfViewers and then add that as a source. I would reccomend watching the tutorials as they explain the classes and what you need in the SDK
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Kinect;
using System.Net.Mail;
using Coding4Fun.Kinect.Wpf;
using Microsoft.Samples.Kinect.WpfViewers;
using System.Diagnostics;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
kinectSensorChooser1.KinectSensorChanged += new DependencyPropertyChangedEventHandler(kinectSensorChooser1_KinectSensorChanged);
}
void kinectSensorChooser1_KinectSensorChanged(object sender, DependencyPropertyChangedEventArgs e)
{
KinectSensor oldSensor = (KinectSensor)e.OldValue;
StopKinect(oldSensor);
KinectSensor newSensor = (KinectSensor)e.NewValue;
newSensor.ColorStream.Enable();
newSensor.DepthStream.Enable();
newSensor.SkeletonStream.Enable();
newSensor.AllFramesReady += new EventHandler<AllFramesReadyEventArgs>(newSensor_AllFramesReady);
try
{
newSensor.Start();
}
catch (System.IO.IOException)
{
kinectSensorChooser1.AppConflictOccurred();
}
}
void StopKinect(KinectSensor sensor)
{
if (sensor != null)
{
sensor.Stop();
sensor.AudioSource.Stop();
}
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
StopKinect(kinectSensorChooser1.Kinect);
}
void newSensor_AllFramesReady(object sender, AllFramesReadyEventArgs e)
{
using (ColorImageFrame colorFrame = e.OpenColorImageFrame())
{
if (colorFrame == null)
{
return;
}
byte[] pixels = new byte[colorFrame.PixelDataLength];
colorFrame.CopyPixelDataTo(pixels);
int stride = colorFrame.Width * 4;
video.Source = BitmapSource.Create(
colorFrame.Width, colorFrame.Height, 96, 96,
PixelFormats.Bgr32, null, pixels, stride);
}
}
Hope this helps.
Related
I am trying to create a GUI that shows small 3 images on the app. When there is a new image in the folder, the new image has to be on the right
side of the imageBoxes. In order to do that, I am using a timer to invoke Load_Form function. The interval is 1000ms. However after some time (
approximately 3:20 min), the program gives an exception "Out of memory" or "Parameter is not valid". Is there another way to update imageboxes automatically( when there is
new image, update it)? The code is here, thank you in advance:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Drawing2D;
using System.Timers;
namespace test1
{
public partial class Form1 : Form
{
string actCode = null;
string pathLogNames = #"D:\LOG\Right";
string[] imPaths;
public Form1()
{
InitializeComponent();
//timer1.Start();
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
string[] getFiles(string path, string text, string fileExtension)
{
try
{
string searchingText = text;
searchingText = "*" + text + "*";
string[] filesArray = Directory.GetFiles(path, searchingText, SearchOption.AllDirectories);
List<string> filesList = new List<string>(filesArray);
List<string> newFilesList = new List<string>();
foreach (string file in filesList)
{
if (file.Contains(fileExtension) == true)
{
newFilesList.Add(file);
}
}
string[] files = newFilesList.ToArray();
return files;
}
catch
{
string[] files = new string[0];
return files;
}
}
string[] viewerPaths;
int pathsNumber;
Image actImage;
Image actImage1;
Image actImage2;
//int actIndex;
double imageDefaultZoom;
public bool mouseFlag = false;
//Point startPoint = new Point();
public void setPaths(string[] paths, double defZoom)
{
viewerPaths = paths;
pathsNumber = viewerPaths.Length;
imageDefaultZoom = defZoom;
int total = viewerPaths.Length;
if (pathsNumber > 0)
{
actImage = Image.FromFile(viewerPaths[total - 3]);
Bitmap b = new Bitmap(actImage);
Image i = resizeImage(b, new Size(100, 100));
pictureBox1.Image = i;
actImage1 = Image.FromFile(viewerPaths[total - 2]);
Bitmap b1 = new Bitmap(actImage1);
Image i1 = resizeImage(b1, new Size(100, 100));
pictureBox2.Image = i1;
actImage2 = Image.FromFile(viewerPaths[total - 1]);
Bitmap b2 = new Bitmap(actImage2);
Image i2 = resizeImage(b2, new Size(100, 100));
pictureBox3.Image = i2;
}
}
private static System.Drawing.Image resizeImage(System.Drawing.Image imgToResize, Size size)
{
//Get the image current width
int sourceWidth = imgToResize.Width;
//Get the image current height
int sourceHeight = imgToResize.Height;
float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;
//Calulate width with new desired size
nPercentW = ((float)size.Width / (float)sourceWidth);
//Calculate height with new desired size
nPercentH = ((float)size.Height / (float)sourceHeight);
if (nPercentH < nPercentW)
nPercent = nPercentH;
else
nPercent = nPercentW;
//New Width
int destWidth = (int)(sourceWidth * nPercent);
//New Height
int destHeight = (int)(sourceHeight * nPercent);
Bitmap b = new Bitmap(destWidth, destHeight);
Graphics g = Graphics.FromImage((System.Drawing.Image)b);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
// Draw image with new width and height
g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
g.Dispose();
return (System.Drawing.Image)b;
}
private void onChanged(object sender, FileSystemEventArgs e)
{
//Dispose();
imPaths = getFiles(pathLogNames, actCode, ".tif");
setPaths(imPaths, 0.5);
}
private void Form1_Load(object sender, EventArgs e)
{
imPaths = getFiles(pathLogNames, actCode, ".tif");
setPaths(imPaths, 0.5);
}
}
}
}
I am trying to send bytes to the "alldata.AddRange()" but I want to do that as line.What I mean,for example, I have a RGB view 640 * 360.Width of the view is 640.I want to take the view 640*3=1920(as a line) and make it gray and send it back to the function(alldata.AddRange).If I send line 360 of them I want to take the image.How can I do that?
EDIT:I changed the code just a little.May be it can be thought as sending data between classes through arrays and I need to send them in parts instead of thinking as image processing problem.
Here is the code for Form1:
using AForge.Video.DirectShow;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace dnm2510img
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public FilterInfoCollection devices;
public VideoCaptureDevice camera;
private void Form1_Load(object sender, EventArgs e)
{
devices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
foreach (FilterInfo item in devices)
{
comboBox1.Items.Add(item.Name);
}
camera = new VideoCaptureDevice();
comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged;
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if (camera.IsRunning == false)
{
camera = new VideoCaptureDevice(devices[comboBox1.SelectedIndex].MonikerString);
camera.NewFrame += Camera_NewFrame;
camera.Start();
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message + "");
}
}
public void Camera_NewFrame(object sender, AForge.Video.NewFrameEventArgs eventArgs)
{
List<byte> alldata = new List<byte>();
//byte[] line = new byte[360];
Bitmap image = (Bitmap)eventArgs.Frame.Clone();
byte[] maindata = new byte[image.Height*image.Width*4];
int count = 0;
if(btnapplyWasClicked == true)
{
for (int i = 0; i < image.Height; i++)
{
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;
maindata[count + 3] = color.A;
count = count + 4;
for (int k = 1; k <= 360; k++)
{
if (maindata[(count + 4) * k] == maindata[2560 * k])
{
dnm2510img.Gray.GrayFilter(maindata, 2560 * k);
}
}
}
}
//alldata.AddRange(maindata);
}
}
private bool btnapplyWasClicked = false;
//private bool button1WasClicked = false;
//private bool GeriALWasClicked = false;
private void btnapply_Click(object sender, EventArgs e)
{
btnapplyWasClicked = true;
}
private void button1_Click(object sender, EventArgs e)
{
//button1WasClicked = true;
}
}
}
Here is the code for Grayscale:
using AForge.Video.DirectShow;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace dnm2510img
{
public class Gray
{
public static byte[] GrayFilter(byte[] data,int width)
{
List<byte> alldataa = new List<byte>();
for (int i = 0; i < width; i++)
{
int temp =((data[i]+data[i+1]+data[i+2]+data[i+3]) / 4);
data[i] = (byte)temp;
data[i+1] = (byte)temp;
data[i+2] = (byte)temp;
data[i + 3] = (byte)temp;
}
//alldataa.AddRange(data);
return data;
}
}
}
This is how you convert a 24 bpp bitmap to grayscale and output it to a linear array:
public static unsafe byte[] ToBgr24To8Mono(Bitmap source)
{
var width = source.Width;
var height = source.Height;
var sourceData = source.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, source.PixelFormat);
var sourceStride = sourceData.Stride;
var sourcePtr = (byte*)sourceData.Scan0;
var targetArray = new byte[width * height];
try
{
Parallel.For(0, height, y =>
{
var sourceRow = sourcePtr + y * sourceStride;
var targetRow = y * width;
for (int x = 0; x < width; x++)
{
var sourceIndex = (sourceRow + x * 3);
var value = (byte) (sourceIndex[0] * 0.11f + sourceIndex[1] * 0.59f + sourceIndex[2] * 0.3f);
targetArray[targetRow + x] = value;
}
});
}
finally
{
source.UnlockBits(sourceData);
}
return targetArray;
}
If you want to use a 32bit image as input, change x * 3 to x * 4. The parallel loop can be switched to a regular loop if you wish.
I need to apply a custom shape (this, a .jpg) to any image I load into my application, using Windows Forms if possible (since my whole project is made in Winforms), but I guess I can use WPF if it's needed.
So for example if I have a photo like this, the result should be like this (I made this with Photoshop for you to see), maybe even without the white borders if possible (please note that the image was resized and centered to fit the custom shape, and that's how it should be).
I can't figure out how to do this, but from what I've searched I suppose it has something to do with brushes (TextureBrush, ImageBrush, etc).
Regards.
it seems to me that you want to apply a mask, you could do it with something like this (using /unsafe code):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace testImageBlender
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Bitmap imBase;
Bitmap imMask,imMask2;
Bitmap blendedImage;
private void Form1_Load(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
if (openFileDialog2.ShowDialog() == DialogResult.OK)
{
imBase = new Bitmap(openFileDialog1.FileName);
imMask = new Bitmap(openFileDialog2.FileName);
blendedImage = new Bitmap(openFileDialog2.FileName);
blendImage();
}
}
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
if (imBase != null)
{
if (imMask != null)
{
if (blendedImage != null)
{
e.Graphics.DrawImage(blendedImage, e.ClipRectangle);
}
}
}
}
private void blendImage()
{
Rectangle mRec = new Rectangle(0, 0, imMask.Width, imMask.Height);
float intensity = 0;
//playing around with images to get pixel format 24bpp RGB, most probably a very bad way of doing it, but I don't know enough about image format and lockbits to do it nice and clean yet
imMask2 = new Bitmap(imMask);
Graphics.FromImage(imBase).DrawImage(imBase, 0, 0, imMask.Width, imMask.Height);
Graphics.FromImage(blendedImage).DrawImage(imMask, 0, 0, imMask.Width, imMask.Height);
Graphics.FromImage(imMask2).DrawImage(imMask, 0, 0, imMask.Width, imMask.Height);
BitmapData imageData = imBase.LockBits(mRec, ImageLockMode.ReadOnly, imBase.PixelFormat);
BitmapData maskData = imMask2.LockBits(mRec, ImageLockMode.ReadOnly, imMask.PixelFormat);
BitmapData blendedData = blendedImage.LockBits(mRec, ImageLockMode.WriteOnly, blendedImage.PixelFormat);
unsafe
{
byte* imagePointer = (byte*)imageData.Scan0;
byte* maskPointer = (byte*)maskData.Scan0;
byte* blendedPointer = (byte*)blendedData.Scan0;
for (int i = 0; i < mRec.Height; i++)
{
for (int j = 0; j < mRec.Width; j++)
{
intensity = 1-((float)(maskPointer[0] + maskPointer[1] + maskPointer[2])) / ((float)3 * 255);
for (int k = 0; k < 3; k++)
{
blendedPointer[k] = (intensity>0.8)?(byte)((float)imagePointer[k]):(byte)255;
}
// 3 bytes per pixel
imagePointer += 3;
maskPointer += 3;
blendedPointer += 3;
}
// Moving the pointers to the next pixel row
imagePointer += imageData.Stride - (mRec.Width * 3);
maskPointer += maskData.Stride - (mRec.Width * 3);
blendedPointer += blendedData.Stride - (mRec.Width * 3);
}
}
imBase.UnlockBits(imageData);
imMask2.UnlockBits(maskData);
blendedImage.UnlockBits(blendedData);
}
}
}
this is very much inspired by Balazs Tihanyi answers on Draw image on top of another image with blending mode color
Here is an example tuned for the image you linked to:
using (var source = (Bitmap) Image.FromFile(#"image filename"))
{
using (var target = new Bitmap(source.Width, source.Height))
{
using (var graphics = Graphics.FromImage(target))
{
using (var path = new GraphicsPath())
{
path.StartFigure();
path.AddLine(161, 665, 223, 624);
path.AddLine(223, 624, 252, 568);
path.AddLine(252, 568, 239, 525);
path.AddLine(239, 525, 200, 432);
path.AddLine(200, 432, 178, 343);
path.AddLine(178, 343, 156, 198);
path.AddLine(156, 198, 161, 131);
path.AddLine(161, 131, 248, 38);
path.AddLine(248, 38, 366, 4);
path.AddLine(366, 4, 657, 10);
path.AddLine(657, 10, 735, 70);
path.AddLine(735, 70, 741, 195);
path.AddLine(741, 195, 746, 282);
path.AddLine(746, 282, 762, 410);
path.AddLine(762, 410, 730, 498);
path.AddLine(730, 498, 686, 582);
path.AddLine(686, 582, 727, 669);
path.CloseFigure();
graphics.Clip = new Region(path);
}
graphics.DrawImage(source, 0, 0);
}
this.PictureBox.Image = new Bitmap(target);
}
}
I'm working in image processing in C# and I have two major error:
Error: Named argument specifications must appear after all fixed arguments have been specified
Error: System.Drawing.Size' is a 'type' but is used like a 'variable'
This is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Emgu.CV;
using Emgu.CV.Structure;
using Emgu.Util;
using Emgu.CV.CvEnum;
using Emgu.CV.GPU;
using Emgu.CV.UI;
namespace SNAKE_C_Sharp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void imageBox1_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
using (OpenFileDialog dialog = new OpenFileDialog())
{
dialog.Filter = "(*.*)|*.*";
if (dialog.ShowDialog() == DialogResult.OK)
{
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
Image image = Image.FromFile(dialog.FileName);
pictureBox1.Image = image;
}
}
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
struct parameter
{
public double alpha { get; set; }
public double beta { get; set; }
public double gamma { get; set; }
};
unsafe private void button3_Click(object sender, EventArgs e)
{
{
int length = 1000;
MCvPoint2D64f* contour;
MCvPoint2D64f center = new MCvPoint2D64f();
var snake_param = new List<parameter>();
snake_param.Add(new parameter { alpha = 0.1, beta = 0.1, gamma = 0.1, });
//Image src_img = pictureBox1.Image;
IntPtr dst_img = new IntPtr();
//IntPtr src_img = Emgu.CV.CvInvoke.cvLoadImage("pictureBox1.Image", Emgu.CV.CvEnum.LOAD_IMAGE_TYPE.CV_LOAD_IMAGE_COLOR);
Bitmap bitmapp = new Bitmap("pictureBox1.Image");
Image<Bgr, byte> image = new Image<Bgr, byte>(bitmapp);
center.x = image.Width;
center.y = image.Height;
int i;
for (i = 0; i < length; i++)
{
contour[i].x = (int)(center.x * Math.Cos(2 * Math.PI * i / length) + center.x);
contour[i].y = (int)(center.y * Math.Sin(2 * Math.PI * i / length) + center.y);
}
for (i = 0; i < length - 1; i++)
{
CvInvoke.cvLine(dst_img, contour[i], contour[i + 1], new MCvScalar(255, 0, 0), 2, lineType: LINE_TYPE.EIGHT_CONNECTED,0);
}
CvInvoke.cvLine(dst_img, contour[length - 1], contour[0], new MCvScalar(255, 0, 0), 2, lineType: LINE_TYPE.EIGHT_CONNECTED, 0);
IntPtr src_img = image.Ptr;
CvInvoke.cvSnakeImage(src_img, contour, length, snake_param[1].alpha, snake_param[2].beta, snake_param[3].gamma, 1.0f, contour[i], System.Drawing.Size(15, 15), new MCvTermCriteria(1, 0.0), true);
CvInvoke.cvCvtColor(src_img, dst_img, COLOR_CONVERSION.GRAY2RGB);
for (i = 0; i < length - 1; i++)
{
CvInvoke.cvLine(dst_img, contour[i], contour[i + 1], new MCvScalar(255, 0, 0), 2, lineType: LINE_TYPE.EIGHT_CONNECTED, 0);
}
CvInvoke.cvLine(dst_img, contour[length - 1], contour[0], new MCvScalar(255, 0, 0), 2, lineType: LINE_TYPE.EIGHT_CONNECTED, 0);
pictureBox2.SizeMode = PictureBoxSizeMode.StretchImage;
Bitmap bitmappbb = new Bitmap("dst_img");
Image<Bgr, byte> imagee = new Image<Bgr, byte>(bitmapp);
pictureBox2.Image = bitmappbb;
}
}
private void imageBox1_Click_1(object sender, EventArgs e)
{
}
private void panAndZoomPictureBox1_Click(object sender, EventArgs e)
{
}
private void imageBox1_Click_2(object sender, EventArgs e)
{
}
}
}
How can i adjust above error?
This is one of the issues that caused error 1
CvInvoke.cvLine(dst_img, contour[i], contour[i + 1], new MCvScalar(255, 0, 0), 2, lineType: LINE_TYPE.EIGHT_CONNECTED,0);
I'll make it more readable...
CvInvoke.cvLine(
dst_img,
contour[i],
contour[i + 1],
new MCvScalar(255, 0, 0),
2,
lineType: LINE_TYPE.EIGHT_CONNECTED,
0
);
See the 2nd-to-last line is using a named argument (lineType:), but is followed by a non-named argument? How is the compiler meant to know what you mean?
The 2nd error is as #LajosArpad stated, you need to add a new in front of your use of System.Drawing.Size(..).
Instead of
CvInvoke.cvSnakeImage(src_img, contour, length, snake_param[1].alpha, snake_param[2].beta, snake_param[3].gamma, 1.0f, contour[i], System.Drawing.Size(15, 15), new MCvTermCriteria(1, 0.0), true);
you need this:
CvInvoke.cvSnakeImage(src_img, contour, length, snake_param[1].alpha, snake_param[2].beta, snake_param[3].gamma, 1.0f, contour[i], new System.Drawing.Size(15, 15), new MCvTermCriteria(1, 0.0), true);
This should fix the second error. Without the new keyword you do not have a System.Drawing.Size instance.
EDIT:
I am not going to test your code, nor to read it line-by-line, so I expect more information about your first error to give you the solution. Can you tell me on which line is the exception thrown?
Also, might I suggest that you should pay more attention to the tabulation of your code, as it is difficult to read if you write your code in such an unstructured manner. It is not impossible to read, but most of us (including myself) will not read it.
I fixed the last error and that's my new code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, System.EventArgs e)
{
using (OpenFileDialog dialog = new OpenFileDialog())
{
dialog.Filter = "JPEG|*.jpg|PNG|*.PNG";
if (dialog.ShowDialog() == DialogResult.OK)
{
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
Image image = Image.FromFile(dialog.FileName);
pictureBox1.Image = image;
}
}
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
}
struct parameter
{
public float alpha { get; set; }
public float beta { get; set; }
public float gamma { get; set; }
};
unsafe private void button3_Click(object sender, EventArgs e)
{
{
int length = 1000;
Point *contour;
Point center = new Point();
var snake_param = new List<parameter>();
snake_param.Add(new parameter { alpha= 0.1f , beta = 0.1f, gamma= 0.1f, });
IntPtr dst_img= new IntPtr();
Bitmap bitmap = new Bitmap("pictureBox1.Image");
Image<Bgr, byte> image = new Image<Bgr, byte>(bitmap);
center.X = image.Width;
center.Y = image.Height;
int i;
for (i = 0; i < length; i++)
{
contour[i].X = (int)(center.X * Math.Cos(2 * Math.PI * i / length) + center.X);
contour[i].Y = (int)(center.Y * Math.Sin(2 * Math.PI * i / length) + center.Y);
}
LINE_TYPE lignetype = new LINE_TYPE();
for (i = 0; i < length - 1; i++)
{
CvInvoke.cvLine(
dst_img,
contour[i],
contour[i + 1],
new MCvScalar(255,0,0),
2,
LINE_TYPE.EIGHT_CONNECTED,
0 );
}
CvInvoke.cvLine
(
dst_img,
contour[length - 1],
contour[0],
new MCvScalar(255,0,0),
2,
LINE_TYPE.EIGHT_CONNECTED,
0
);
IntPtr ctr =new IntPtr();
//public void PixelToInkSpace(
//IntPtr a
//ref Point contour
//);
IntPtr src_img = image.Ptr;
CvInvoke.cvSnakeImage(
src_img,
contour[i],
length,
snake_param.[1].alfa,
snake_param[2].beta,
snake_param[3].gamma,
1,
new System.Drawing.Size(15, 15),
new MCvTermCriteria(1,0.0),
1);
CvInvoke.cvCvtColor(
src_img,
dst_img,
COLOR_CONVERSION.GRAY2RGB );
for (i = 0; i < length - 1; i++)
{
CvInvoke.cvLine(
dst_img,
contour[i],
contour[i + 1],
new MCvScalar(255,0,0),
2,
LINE_TYPE.EIGHT_CONNECTED,
0 );
}
CvInvoke.cvLine(
dst_img,
contour[length - 1],
contour[0],
new MCvScalar(255,0,0),
2,
LINE_TYPE.EIGHT_CONNECTED,
0);
pictureBox2.SizeMode = PictureBoxSizeMode.StretchImage;
Bitmap bitmappbb = new Bitmap("dst_img");
Image<Bgr, byte> imagee = new Image<Bgr, byte>(bitmappbb);
pictureBox2.Image = bitmappbb;
}
}
}
}
But my error now is different as I'm translating my code from c++ to c# ,
I discover that the snake format is
public static void cvSnakeImage(
IntPtr image,
IntPtr points,
int length,
float[] alpha,
float[] beta,
float[] gamma,
int coeffUsage,
Size win,
MCvTermCriteria criteria,
bool calcGradient
)
I didn't find way to convert the variable "contour" with type "Point" to "IntPtr".
And a way to call alfa, beta et gamma as float[];
#Timothy Walters
Let me start off by saying that I have indeed followed many tutorials such as the one located on EmguCv's main site in their entirety but get a TypeInitializationException thrown.
Now, listen closely because here comes the extremely weird part. I'll start by saying that there are three "levels" of my problem, however, the code in all "levels" is EXACTLY the same without even the slightest of change. This would naturally point to that I have a reference or linkage problem, but again I've attempted multiple attempts following different tutorials but to no avail.
Level 1 (this level produces a TypeInitializationException)
I create a new project, properly reference everything and such, then write my code in this new project. Upon debug, I get that exception thrown and my program exits. Here's a link to a picture of the problem: http://prntscr.com/uychc
Level 2 (this level runs completely fine and no exception is thrown)
In this level, I pretty much located one of EmguCv's example projects (VideoSurveilance in this case) then delete the default code and copy and paste all of my code in there. After adding a few more references that I needed, the program works fine. I cant post more than 3 links, but you'll have to trust me that the video picture displays correctly.
Level 3 (this level does not throw an exception but warns me of a "first chance" of one)
In this level, I copy and paste my whole Level 2 project into a different directory. After finding and relinking missing files/references, I am able to run the program but the pictures do not show and I get a "A first chance exception of type "System.TypeInitializationException" occurred in Emgu.CV.dll warning. http://prntscr.com/uycmn
I currently run Windows 7 x64 (yes I changed build options to x64 and x64 .dlls) and am running EmguCv 2.4.9 and 2.4.2 (tested on both) and Visual Studios 2010 and 2012 (tested on both).
Here's the code for what it may be worth:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
//using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Kinect;
using Emgu.CV;
using Emgu.CV.CvEnum;
using Emgu.CV.Structure;
using Emgu.CV.UI;
using System.IO;
namespace VideoSurveilance
{
public partial class VideoSurveilance : Form
{
KinectSensor sensor;
WriteableBitmap depthBitmap;
WriteableBitmap colorBitmap;
DepthImagePixel[] depthPixels;
byte[] colorPixels;
int blobCount = 0;
public VideoSurveilance()
{
InitializeComponent();
}
private void VideoSurveilance_Load(object sender, System.EventArgs e)
{
foreach (var potentialSensor in KinectSensor.KinectSensors)
{
if (potentialSensor.Status == KinectStatus.Connected)
{
this.sensor = potentialSensor;
break;
}
}
if (null != this.sensor)
{
this.sensor.DepthStream.Enable(DepthImageFormat.Resolution640x480Fps30);
this.sensor.ColorStream.Enable(ColorImageFormat.RgbResolution640x480Fps30);
this.colorPixels = new byte[this.sensor.ColorStream.FramePixelDataLength];
this.depthPixels = new DepthImagePixel[this.sensor.DepthStream.FramePixelDataLength];
this.colorBitmap = new WriteableBitmap(this.sensor.ColorStream.FrameWidth, this.sensor.ColorStream.FrameHeight, 96.0, 96.0, PixelFormats.Bgr32, null);
this.depthBitmap = new WriteableBitmap(this.sensor.DepthStream.FrameWidth, this.sensor.DepthStream.FrameHeight, 96.0, 96.0, PixelFormats.Bgr32, null);
WriteableBitmap bitmap;
bitmap = new WriteableBitmap(this.sensor.DepthStream.FrameWidth, this.sensor.DepthStream.FrameHeight, 96.0, 96.0, PixelFormats.Bgr32, null);
byte[] retVal = new byte[bitmap.PixelWidth * bitmap.PixelHeight * 4];
bitmap.CopyPixels(new Int32Rect(0, 0, bitmap.PixelWidth, bitmap.PixelHeight), retVal, bitmap.PixelWidth * 4, 0);
Bitmap b = new Bitmap(bitmap.PixelWidth, bitmap.PixelHeight);
int k = 0;
byte red, green, blue, alpha;
for (int i = 0; i < bitmap.PixelWidth; i++)
{
for (int j = 0; j < bitmap.PixelHeight && k < retVal.Length; j++)
{
alpha = retVal[k++];
blue = retVal[k++];
green = retVal[k++];
red = retVal[k++];
System.Drawing.Color c = new System.Drawing.Color();
c = System.Drawing.Color.FromArgb(alpha, red, green, blue);
b.SetPixel(i, j, c);
}
}
Image<Bgr, Byte> temp = new Image<Bgr, byte>(b);
this.ibOriginal.Image = temp;
this.sensor.AllFramesReady += this.sensor_AllFramesReady;
try
{
this.sensor.Start();
}
catch (IOException)
{
this.sensor = null;
}
}
}
private void sensor_AllFramesReady(object sender, AllFramesReadyEventArgs e)
{
blobCount = 0;
BitmapSource depthBmp = null;
Image<Bgr, Byte> openCVImg;
using (ColorImageFrame colorFrame = e.OpenColorImageFrame())
{
using (DepthImageFrame depthFrame = e.OpenDepthImageFrame())
{
if (depthFrame != null)
{
blobCount = 0;
if (colorFrame != null)
{
byte[] pixels = new byte[colorFrame.PixelDataLength];
colorFrame.CopyPixelDataTo(pixels);
int stride = colorFrame.Width * 4;
BitmapSource color = BitmapImage.Create(colorFrame.Width, colorFrame.Height, 96, 96, PixelFormats.Bgr32, null, pixels, stride);
openCVImg = new Image<Bgr, byte>(color.ToBitmap());
}
else
{
return;
}
Image<Gray, byte> gray_image;
using (MemStorage stor = new MemStorage())
{
gray_image = openCVImg.InRange(new Bgr(0, 0, 150), new Bgr(200, 200, 255));
gray_image = gray_image.SmoothGaussian(9);
CircleF[] circles = gray_image.HoughCircles(new Gray(100),
new Gray(50),
2,
gray_image.Height / 4,
10,
400)[0];
foreach (CircleF circle in circles)
{
CvInvoke.cvCircle(openCVImg,
new System.Drawing.Point(Convert.ToInt32(circle.Center.X), Convert.ToInt32(circle.Center.Y)),
3,
new MCvScalar(0, 255, 0),
-1,
LINE_TYPE.CV_AA,
0);
openCVImg.Draw(circle,
new Bgr(System.Drawing.Color.Red),
3);
}
}
ibOriginal.Image = openCVImg;
ibProcessed.Image = gray_image;
}
}
}
}
}
}
using System;
using System.Globalization;
using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Microsoft.Kinect;
using System.ComponentModel;
using System.Runtime.InteropServices;
using Emgu.CV;
namespace VideoSurveilance
{
public static class Helper
{
private const int MaxDepthDistance = 4000;
private const int MinDepthDistance = 850;
private const int MaxDepthDistanceOffset = 3150;
public static BitmapSource SliceDepthImage(this DepthImageFrame image, int min = 20, int max = 1000)
{
int width = image.Width;
int height = image.Height;
//var depthFrame = image.Image.Bits;
short[] rawDepthData = new short[image.PixelDataLength];
image.CopyPixelDataTo(rawDepthData);
var pixels = new byte[height * width * 4];
const int BlueIndex = 0;
const int GreenIndex = 1;
const int RedIndex = 2;
for (int depthIndex = 0, colorIndex = 0;
depthIndex < rawDepthData.Length && colorIndex < pixels.Length;
depthIndex++, colorIndex += 4)
{
// Calculate the distance represented by the two depth bytes
int depth = rawDepthData[depthIndex] >> DepthImageFrame.PlayerIndexBitmaskWidth;
// Map the distance to an intesity that can be represented in RGB
var intensity = CalculateIntensityFromDistance(depth);
if (depth > min && depth < max)
{
// Apply the intensity to the color channels
pixels[colorIndex + BlueIndex] = intensity; //blue
pixels[colorIndex + GreenIndex] = intensity; //green
pixels[colorIndex + RedIndex] = intensity; //red
}
}
return BitmapSource.Create(width, height, 96, 96, PixelFormats.Bgr32, null, pixels, width * 4);
}
public static byte CalculateIntensityFromDistance(int distance)
{
// This will map a distance value to a 0 - 255 range
// for the purposes of applying the resulting value
// to RGB pixels.
int newMax = distance - MinDepthDistance;
if (newMax > 0)
return (byte)(255 - (255 * newMax
/ (MaxDepthDistanceOffset)));
else
return (byte)255;
}
public static System.Drawing.Bitmap ToBitmap(this BitmapSource bitmapsource)
{
System.Drawing.Bitmap bitmap;
using (var outStream = new MemoryStream())
{
// from System.Media.BitmapImage to System.Drawing.Bitmap
BitmapEncoder enc = new BmpBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(bitmapsource));
enc.Save(outStream);
bitmap = new System.Drawing.Bitmap(outStream);
return bitmap;
}
}
[DllImport("gdi32")]
private static extern int DeleteObject(IntPtr o);
/// <summary>
/// Convert an IImage to a WPF BitmapSource. The result can be used in the Set Property of Image.Source
/// </summary>
/// <param name="image">The Emgu CV Image</param>
/// <returns>The equivalent BitmapSource</returns>
public static BitmapSource ToBitmapSource(IImage image)
{
using (System.Drawing.Bitmap source = image.Bitmap)
{
IntPtr ptr = source.GetHbitmap(); //obtain the Hbitmap
BitmapSource bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
ptr,
IntPtr.Zero,
Int32Rect.Empty,
System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
DeleteObject(ptr); //release the HBitmap
return bs;
}
}
}
}
I sincerely thank anyone who even attempts to help me and hope that anyone with similar problems can benefit from this long question.
Found 'brute force' solution:
you have to put the "cvextern.dll" file into your build directory (x64, debug, release, or whatever) manually.
this does the job. I can't believe I spent a whole day trying to figure this out.
As Oliver said you, your problem is very similar to this one : EmguCV TypeInitializationException
The exception is thrown by an impossibility to access some dll as opencv_highgui220.dll. In CvInvoke you will find DLLImports, maybe you should insert a break point and observe what it comes.
I suppose you have already read this from emgu website