OpenCvSharp: CvtSeqToArray crashes - c#

I am searching a contour, and at least one is found, as I can see with the debugger.
When I try to transform the sequence into an array of points a StackOverflowException (that's why I am here :-) is thrown.
I am sure the reason is some wrong allocation of buffers, I am a bit confused with the examples I have found in C, C++, but not in C#. OpenCvSharp uses generics which I never used before.
Platform: Windows 7 on x86, Sharpdevelop 4.2.2
Here follows the code snippet:
OpenCvSharp.CvMemStorage allContours = new OpenCvSharp.CvMemStorage();
OpenCvSharp.CvSeq<OpenCvSharp.CvPoint> contour = null;
OpenCvSharp.CvPoint[] border;
i = OpenCvSharp.Cv.FindContours (image[EDGE], allContours, out contour,
OpenCvSharp.CvContour.SizeOf, OpenCvSharp.ContourRetrieval.List,
OpenCvSharp.ContourChain.ApproxNone,
OpenCvSharp.Cv.Point(0,0));
if (i!=1)
{ Forms.MessageBox.Show( i.ToString() + " instead of 1 contours found", "Info");
return;
}
border = new OpenCvSharp.CvPoint [contour.Total];
OpenCvSharp.Cv.CvtSeqToArray<OpenCvSharp.CvPoint> (contour, out border);
It is the last line where the program crashes.

Related

How to list all APKs with isGame flag set to true?

I got this code:
_pm = _context.PackageManager;
List<string> packageList = new List<string>();
Intent intent = new Intent(Intent.ActionMain);
intent.AddCategory(Intent.CategoryLeanbackLauncher);
var list = _pm.QueryIntentActivities(intent, PackageInfoFlags.MetaData);
var counter = 0;
foreach (var app in list)
{
counter++;
ApplicationInfo ai = _pm.GetApplicationInfo(app.ActivityInfo.PackageName, 0);
if (filter.Equals(IApplicationsControl.Filter.AppsOnly))
{
if (ai.Category != ApplicationCategories.Game)
{
Android.Util.Log.Debug("pm", counter + ". " + ai.Category + " - " + app.ActivityInfo.PackageName);
packageList.Add(app.ActivityInfo.PackageName);
}
}
}
The output:
1. Undefined - com.android.vending
2. Undefined - com.google.android.youtube.tv
3. Undefined - com.myApp.test1
4. Undefined - com.android.traceur
5. Undefined - com.arris.android.stb.rcu
6. Undefined - com.arris.upgradetest
7. Undefined - com.clearchannel.iheartradio.application.tvapplication
8. Undefined - com.ericsson.tv
9. Audio - com.google.android.music
10. Undefined - com.google.android.play.games
11. Undefined - com.uei.uassample
12. Undefined - com.FDGEntertainment.redball4.gp <--- this is a game
13. Undefined - com.fgol.HungrySharkEvolution <--- this is a game
14. Undefined - com.hyperkani.bomberfriends <--- this is a game
15. Undefined - com.madfingergames.deadtrigger2 <--- this is a game
16. Undefined - com.secretexit.turbodismount <--- this is a game
17. Undefined - com.vectorunit.purple.googleplay
I installed several games, such as Hungry Shark and DeadTrigger2, I opend the APKs and both applications got the isGame:true set in their AndroidManifest.xml files.
The code above is listing the categories of my apps as Undefined, this includes my 2 games, it's like that for nearly all of my apps, except some AUDIO app that plays music.
So, in the end, why does my code not work?
I was following this links:
How to check if the app is game or not programmatically?
Also, I found this one, that concerns me a lot:
How can check app is game or not android?
So in the end, is it even possible now to check if an app is a game or not?
My API lvl is 28+
Ofcourse, I searched 2 days without an answer, and then finally decided to post a question here, and ofcourse now i found an answer.
_pm = _context.PackageManager;
List<string> packageList = new List<string>();
Intent intent = new Intent(Intent.ActionMain);
intent.AddCategory(Intent.CategoryLeanbackLauncher);
var list = _pm.QueryIntentActivities(intent, PackageInfoFlags.MetaData);
foreach (var app in list)
{
ApplicationInfo ai = _pm.GetApplicationInfo(app.ActivityInfo.PackageName, 0);
var allFlags = ai.Flags;
if (allFlags.HasFlag(ApplicationInfoFlags.IsGame))
{
packageList.Add(app.ActivityInfo.PackageName);
}
}
What did I do? I saw, out of pure luck, that the ApplicationInfo variable ai, got a field Flags, that contain the correct flag, (not the flag FLAG_IS_GAME nor ApplicationCategories.Game)) also, I found the right class to pick the IsGame from (ApplicationInfoFlags.IsGame)
The rest is simple.
The conclusion, is that the approach to get the information about the app beeing a game or not about the category, or the FLAG_IS_GAME seems not to work as it should.
This worked for me, and hopefully the next guy in the same problem :)

EmguCV Access Violation Exception while using BlobFromImage

I've been trying for a long time to implement pose detection in EmguCV without success.
I have a successful program in C++ using OpenCV. When I tried to translate it in C#, I couldn't go over the "BlobFromImage" because I get an Exception ("Access Violation")...
I tried multiple things, I'm compiling in x64, and the image is correct (I can show it without problem as an image). Before that I was using Mat instead of UMat, but it's just the same.
Emgu version: 4.2.0.3662 (also tried with other versions, still getting the same error.
If it can help, see the code below:
private void Prova()
{
VideoCapture cap = new VideoCapture(videoFile);
if (!cap.IsOpened)
{
Debug.WriteLine("Unable to connect to camera");
return;
}
UMat frame;
int frameWidth = (int)cap.GetCaptureProperty(Emgu.CV.CvEnum.CapProp.FrameWidth);
int frameHeight = (int)cap.GetCaptureProperty(Emgu.CV.CvEnum.CapProp.FrameHeight);
VideoWriter video = new VideoWriter("Output-Skeleton-Davide-MPI-GPU-168.avi", VideoWriter.Fourcc('M', 'J', 'P', 'G'), new System.Drawing.Size(frameWidth, frameHeight), false);
Net net = Emgu.CV.Dnn.DnnInvoke.ReadNetFromCaffe("./pose_deploy_linevec.prototxt", "./pose_iter_160000.caffemodel");
net.SetPreferableBackend(Emgu.CV.Dnn.Backend.Default);
net.SetPreferableTarget(Emgu.CV.Dnn.Target.OpenCL);
frame = cap.QueryFrame().GetUMat(Emgu.CV.CvEnum.AccessType.ReadWrite);
if (frame.Rows != 0 && frame.Cols != 0)
{
// Exception thrown here...
Emgu.CV.UMat inpBlob = Emgu.CV.Dnn.DnnInvoke.BlobFromImage(frame).GetUMat(Emgu.CV.CvEnum.AccessType.ReadWrite);
net.SetInput(inpBlob);
}
}
I know that I could call the c++ code from C#, but I would rather do it from C# alone.
Thanks a lot

Error: 'The process cannot access the file because it is being used by another process' in Visual Studio c#

I am having some trouble with this error in Visual Studio:
An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll
Additional information: The process cannot access the file 'C:\Users\aheij\Desktop\KinectOutput\swipe.txt' because it is being used by another process.
What I Have tried:
I have tried using these codes obtained from other solved StackOverflow questions similar to mine to try to solve the problem - but even that didn't seem to work?
Ive tried checking if the file is in use, but with no success.
I also run Visual Studio as administrator.
The file is not read-only.
The folder is not open, and the file is not being used in any other program when executing the code - at least not that I can see/know of.
The code:
So, to add some context to my code: I am writing some quick gesture detection code to the Kinect c# BodyBasics SDK v2 code freely available. This is a helper method that I added, that gets called in when a person is in view. If that person is executing the gesture, the method writes the frame time and gesture name to a text file.
Half the time, when the code does work, the gesture recognition works well. However, the other half of the time, the code breaks/stops because the writing to file bit causes the error.
Below is my code to see if the person is standing in the neutral position - its a bit waffly, so apologies about that. I have commented 'ERROR' where the error is (unsurprisingly):
private void Neutral_stance(VisualStyleElement.Tab.Body body, IReadOnlyDictionary<JointType, Joint> joints, IDictionary<JointType, Point> jointPoints, BodyFrame bf)
{
CameraSpacePoint left_hand = joints[JointType.HandLeft].Position;
CameraSpacePoint left_elbow = joints[JointType.ElbowLeft].Position;
CameraSpacePoint left_shoulder = joints[JointType.ShoulderLeft].Position;
CameraSpacePoint left_hip = joints[JointType.HipLeft].Position;
CameraSpacePoint right_hand = joints[JointType.HandRight].Position;
CameraSpacePoint right_elbow = joints[JointType.ElbowRight].Position;
CameraSpacePoint right_shoulder = joints[JointType.ShoulderRight].Position;
CameraSpacePoint right_hip = joints[JointType.HipRight].Position;
double vertical_error = 0.15;
double shoulderhand_xrange_l = Math.Abs(left_hand.X - left_shoulder.X);
double shoulderhand_xrange_r = Math.Abs(right_hand.X - right_shoulder.X);
if (bf != null)
{
TimeSpan frametime = bf.RelativeTime;
string path_p = #"C:\Users\aheij\Desktop\KinectOutput\Punch.txt"; //write to punch file
string path_s = #"C:\Users\aheij\Desktop\KinectOutput\swipe.txt"; //write to swipe file
if (left_hand.Y < left_elbow.Y)
{
if (right_hand.Y < right_elbow.Y)
{
if (shoulderhand_xrange_l < vertical_error)
{
if (shoulderhand_xrange_r < vertical_error)
{
Gesture_being_done.Text = " Neutral";
File.AppendAllText(path_p, frametime.ToString() + " Neutral" + Environment.NewLine); //ERROR
File.AppendAllText(path_s, frametime.ToString() + " Neutral" + Environment.NewLine); //ERROR
}
}
}
}
else
{
Gesture_being_done.Text = " Unknown";
File.AppendAllText(path_p, frametime.ToString() + " Unknown" + Environment.NewLine); //ERROR
File.AppendAllText(path_s, frametime.ToString() + " Unknown" + Environment.NewLine); //ERROR
}
}
}
Any solutions/ideas/suggestions to point me on the right track would be appreciated. I think that it would be good to use the 'using streamwriter' method as opposed to the method I am using here - but I am not sure how? Any help would be appreciated.
Additonal Info: Using Visual Studio 2015; Using windows 10.
Sidenote: I read somewhere that the Windows Search tool in Windows 10 can interfere and cause problems like this so I need to disable it?
As suggested to me I used the Filestream method & ensured the file was closed after use. But, even this still caused the same error.
Thus, I also got rid of having two file-writing actions in rapid succession of each other. I dont know if this is technically right or even true, but based off of this post here: link, my error could be coming up because I am trying to execute the second 'write to text file' line whilst the previous 'write to text file' line is still executing/writing to that same folder & location - hence the clash? Please someone, correct me if I am wrong.
Either way, this seems to have worked.
See below for my edited/corrected method:
private void Neutral_stance(Body body, IReadOnlyDictionary<JointType, Joint> joints, IDictionary<JointType, Point> jointPoints, BodyFrame bf)
{
//cameraspace point joint stuff here again (see original post for this bit leading up to the if statements.)
if (bf != null)
{
TimeSpan frametime = bf.RelativeTime;
string path_s = #"C:\Users\aheij\Desktop\KinectOutput\swipe.txt";
if (left_hand.Y < left_elbow.Y)
{
if (right_hand.Y < right_elbow.Y)
{
if (shoulderhand_xrange_l < vertical_error)
{
if (shoulderhand_xrange_r < vertical_error)
{
Gesture_being_done.Text = " Neutral";
FileStream fs_s = new FileStream(path_s, FileMode.Append); //swipe
byte[] bdatas = Encoding.Default.GetBytes(frametime.ToString() + " Neutral" + Environment.NewLine);
fs_s.Write(bdatas, 0, bdatas.Length);
fs_s.Close();
}
}
}
}
else
{
Gesture_being_done.Text = " Unknown";
FileStream fs_s = new FileStream(path_s, FileMode.Append);
byte[] bdatas = Encoding.Default.GetBytes(frametime.ToString() + " Unknown" + Environment.NewLine);
fs_s.Write(bdatas, 0, bdatas.Length);
fs_s.Close();
}
}
}
Do let me know if there is any way I can make this more elegant or anything else I should be aware of w.r.t this answer.
The code is based off of the code found here: FileStream Tutorial website

IOS Marshal.PtrToStructure System.ExecutionEngineException

Hey I was wondering if there is a fix for the following issue as i can't seem to find one anywhere and I have now ran out of ideas.
I am writing a program using Xamarin.Forms to run across both android and IOS, the following both code versions work on android, However throws a ExecutionEngineException when the second version is ran on IOS but the first one works.
protected static object ReadStruct(BinaryReader reader, Type structType, ChunkHeader chunkHeader)
{
int size = Marshal.SizeOf(structType);
if (size != chunkHeader.chunkSize) // check the actual size of this chunk object with the expected size from the stream
{
throw new IOException("Invalid file format, incorrect " + chunkHeader.chunkName + " chunk size (exp.: " + size + ", read: " + chunkHeader.chunkSize + ")");
}
byte[] data = reader.ReadBytes(size);
IntPtr buffer = Marshal.AllocHGlobal(size);
Marshal.Copy(data, 0, buffer, size);
// the line that crashes follows this
object structObject = Marshal.PtrToStructure(buffer, structType);
Marshal.FreeHGlobal(buffer);
return structObject;
}
The above code stays the same in both versions.
public struct OvdBChunk
{
// stuff in here but not important
}
The above sample works but for this and all future updates i will need to inherit the old versions as stuff may have been updated in newer devices so have been added to but will always keep the old stuff so i changed it to the following
public class OvdBChunk : OvdAChunk
{
// stuff in here but not important
}
The structType in part is the part that is changing in the top code snippet.
Any idea why when it is a class instead of a strut it throws the System.ExecutionEngineException. and any ideas on how i can fix it?

OpenCL Cloo: Out of Resources Error

While running some test code in OpenCL (using Cloo C#), I started getting these OutOfResource errors from OpenCL and sometimes Unity just crashes entirely before I get an exception. I am basically re-calling a kernel function over and over with varying number of global/local work items to check timing. I leave the arguments the same and call the kernel starting with 2x2x2 global and 2x2x2 local and iterating uperwards checking only valid sizes. It works fine occasionally, but most of the time it completes about 30 or 40 Execute() calls and then crashes on the next Execute() call.
Note: Execute refers to the OpenCL.dll on the computer. The stack trace Unity returns is NULL I assume because of the native code.
Anyone have any idea what could be causing this?
Note: This version of Cloo is Cloo-Unity from GitHub and I am using it in Unity. The equivalent OpenCL function being called when I get the error is clEnqueueNDRangeKernel(), but it is called Execute() in Cloo.
Code Sample:
//Setup inputs one time...
foreach (var input in p_inputs)
{
inputs.Add(input.Function, input);
profiles.Add(input.Function, new RunProfile(input.Function, input.Weight));
input.Input.Prepare(package[input.Function]);
}
//Profile...
DateTime start;
int g_state = 0;
int l_state = 0;
long[] g = new long[3] { 2, 2, 2 };
long[] l = new long[3] { 2, 2, 2 };
while(g[0] * g[1] * g[2] < Device.MaxWorkGroupSize)
{
l[0] = 2; l[1] = 2; l[2] = 2; l_state = 0; //Reset locals
bool proceed = true;
while(proceed)
{
proceed = (l[0] != g[0] || l[1] != g[1] || l[2] != g[2]);
if (CLUtilities.ValidateExecutionParameters(Device, g, l))
{
Debug.Log("Profiling Start: " + g.ToEnumeratedString() + " / " + l.ToEnumeratedString());
foreach (var profile in profiles)
{
start = DateTime.Now;
//Exception here when on (g=6x4x4, l=6x4x4)
package.Execute(package[profile.Key], g, l);
package.Commands.Flush();
package.Commands.Finish();
float time = (float)(DateTime.Now - start).TotalMilliseconds;
profile.Value.AddRun(g, l, time);
}
Debug.Log("Profiling Ending: " + g.ToEnumeratedString() + " / " + l.ToEnumeratedString());
}
l[l_state] += 2;
l_state = (l_state == 2) ? 0 : l_state + 1;
}
g[g_state] += 2;
g_state = (g_state == 2) ? 0 : g_state + 1;
}
Sorry i cannot comment cause less than 50 rep. but which operating system do you use? gpu? driver?
i got similar problems caused by opencl.dll i used win10 and Nvidia (x64).
Also have a look on https://social.technet.microsoft.com/Forums/en-US/85680348-c2c4-40bc-9f39-9dcfeea331c0/windows-10-opencldll-error?forum=win10itprogeneral
It seems that there is/was a issue with the memory compression in win10.
My problem was caused by updating win7 to win10, without updating the nvidia drivers.
I just got back around to posting this, but the issue turned out be related to the fact that I didn't recall Kernel.SetArgument() each time I called the Execute() method. I originally did this because I was worried it would re-copy the buffer, but as it turns out the buffer copy doesn't occur in this method anyway (so the overhead was small anyway).
Does your nvidia graphics card for display?
If nvidia is main graphics card, you have to edit registry to turn off watchdog.
for windows 7
system/current/control/graphicsdriver
TdrLevel(DWORL) : 0

Categories

Resources