secile / usbcamera Goto Github PK
View Code? Open in Web Editor NEWC# source code for using usb camera and web camera in WinForms/WPF. With only single CSharp source code. No external library required.
License: MIT License
C# source code for using usb camera and web camera in WinForms/WPF. With only single CSharp source code. No external library required.
License: MIT License
I stop the old camera and create a new camera ,then start it,It doesn't work.
I want to make the class public for acces the webcam from diferents files of codes thanks
Hello @secile,
What you have here is gold. Thank you for putting it together.
Is it possible to pass a callback function on capture? This is essential for cameras which have an external capture button. We need to have a way to detect it and either manually trigger a GetBitmap or the event will take one and pass it to the callback function.
Hello,
I don't know if I am asking right question..
But for last few days, I have been looking for a way to write a device driver that can recognize connected cameras on computer/laptops via USB port, as a video input source on streaming software like OSB.
I just want to know how your code works and if there is a way to create such device driver?
Thanks in Advance..
Since the use of events is rather an outdated technique, I would be happy if you would also implement the IObservable
pattern in your library.
This would make it more than easy to use your library in conjunction with system.reactive. 🍻
When the usbcamera has lights,the lights will be turned on
after executing code {moniker.BindToObject(null, null, ref guid, out value)}.
But the light is not turned off after {*** usbcamera.Relase().*** }.
How can I turn off the lights?
This issue is related to issue#27
To reduce memory consumption, when I replace code
from
var timer = new System.Timers.Timer(1000 / 30) { SynchronizingObject = this };
timer.Elapsed += (s, ev) => pictureBox1.Image = camera.GetBitmap();
timer.start();
to
var timer = new System.Timers.Timer(1000 / 30) { SynchronizingObject = this };
timer.Elapsed += (s, ev) =>
{
var oldImage = pictureBox1.Image;
pictureBox1.Image = camera.GetBitmap();
oldImage?.Dispose();
};
timer.Start();
It happens ''ArgumentException" the line below.
pictureBox1.Image = camera.GetBitmap(); // happens exception.
take over from issue #13
I found that it is necessary to return quickly in callback function.
if callback does not return quickly, it can interfere with playback.
https://docs.microsoft.com/en-us/windows/win32/directshow/isamplegrabber-setcallback
This is previous version document, it is prohibited to enter critical section.
https://docs.microsoft.com/en-us/previous-versions/ms786692(v=vs.85)
It is better do not enter critical section and do not wait another thread.
public int BufferCB(double SampleTime, IntPtr pBuffer, int BufferLen)
{
if (Buffer == null || Buffer.Length != BufferLen)
{
Buffer = new byte[BufferLen];
}
var locked = false;
try
{
System.Threading.Monitor.TryEnter(BufferLock, 0, ref locked);
if (locked)
{
Marshal.Copy(pBuffer, Buffer, 0, BufferLen);
}
}
finally
{
if (locked) System.Threading.Monitor.Exit(BufferLock);
}
return 0;
}
Using a The Imaging Source USB 3.1 1440 x 1080 px camera sometimes, especially at the beginning, the preview freezes and you have to do Camera.Stop() + Camera.Start() to make it restart. What could it be?
Hello @secile,
We deployed the latest version, and we have this observation. The Still Pin works on some Cameras but it doesn't on some other cameras. To be accurate, it was tested on 3 cameras, only 1 worked.
Could there be anything missed in the code? We have access to one of the cameras that didn't work, so if there is anything to check to troubleshoot this issue we will be happy to do.
I am using your work with satisfaction and I would like to know, since some cameras have a serial code, would it be possible to read it?
Thank you for your creative work, it's really great!
When I read the source code, I found that when SampleGrabberCallback uses the system thread pool for processing, all available threads in the thread pool (other threads not actually used by the library) will be blocked by BufferedEvent, and other modules using the system thread pool in the same application will be restricted. As a library that may be referenced by many programs, I think this approach should be avoided in design. It may be better to use a thread that implements a simple event queue to do this.
if my understanding of this program is correct?
public SampleGrabberCallback(DirectShow.ISampleGrabber grabber, int width, int height, int stride, bool useCache)
{
this.BmpBuilder = new BitmapBuilder(width, height, stride, useCache);
// create Buffered.Invoke thread.
System.Threading.ThreadPool.QueueUserWorkItem(x =>
{
while (true)
{
BufferedEvent.WaitOne(); // wait event.
Buffered?.Invoke(GetBitmap()); // fire!
}
});
grabber.SetCallback(this, 1); // WhichMethodToCallback = BufferCB
}
I'm making a movement detector with your awesome class but going through image GetPixel and SetPixel is very slow so it would be great if that could be possible
First of all I would like to thank you for the library! Really impressive and kept simple 👍
Finally, to use your code, I added the UsbCamera.cs to my project. It would be nice if you could also provide us with a nuget package (taking versioning into account; see https://github.com/GitTools/GitVersion).
// create instance.
camera = new UsbCamera(cameraIndex, format);
// show preview on control. (works light.)
camera.SetPreviewControl(this.panVideo.Handle, this.panVideo.ClientSize);
private void panVideo_MouseMove(object sender, MouseEventArgs e)
{
//it never fired over the camera region.but fired over other whitespace region.
Console.WriteLine("mouse move");
}
Do you happen to know if anything can be done to avoid screen tearing while capturing at higher resolutions?
For instance, if I capture at 2592 x 1944 (~5 MP), I get this kind of artifacts:
Seemingly there's not much that can be done within the class (method GetBitmapMainMain()
). This is how the local data
buffer is copied from the unmanaged DirectShow buffer - already teared. Any settings for DirectShow maybe, or is there not much hope?
Your code is very good.
But I have confirmed some problems.
Currently implemented code is to get a camera list, select a camera (select an index value), and connect.
But What I want is to save the name/ID of the camera and extract the matching index value.
and than I want to connect after extracting the index value. (Automatic connection)
(The index of each camera is changed every time because the camera can be changed, broken, or newly added.
It cannot be used as a specification because the camera cannot be selected every time)
At first,
I tried to use the camera name and [VideoFormat] as specifications
(Find the camera name and the [VideoFormat] Find the index value)
However, when using the cameras of the same product, Since the name is the same, the method cannot be used.
I want an ID like Aforge.video.directShow -Filtermoniker,
In the Videoo format [] GetVideoFormat (int Cameraidex) function, m_symboliclik is identified as Aforge.video.directShow -Filtermoniker.
but it could not be used becuase it is IUNKNOWN type
Is it possible to add m_symboliclink value to the [VideoFormat] for distinction between cameras?
Can you tell me if there is a better way?
Thank you very much
Why fps = 1 or2 only at 3840 * 2160 resolution? if 1920 * 1080 its nomal at 30 fps.
下载并安装 非标的虚拟摄像头(例如 YY开播)
(Download and install non-standard cameras such as 'YY开播')
YY开播
FindDevices 成功获取到 ‘YY开播’
(find 'YY开播’ success by FindDevices )
造成这个的原因是 ‘YY开播’ 注册了一个信息不完整的USB摄像头
(The reason for this is that a USB camera with incomplete information has been registered by 'YY开播')
问题是我们没办法限制用户不要安装什么软件
(The problem is that we can't restrict users from installing any software)
我发现在 GetFiltes 时 'YY开播' 无法获取到 DevicePath
(I found that 'YY开播' could not get DevicePath when GetFiltes)
所以 尝试获取 DevicePath 或许是一个过滤非标虚拟摄像头的方式
(So trying to get DevicePath may be a way to filter non-standard virtual cameras)
我发现 FlashCap 并没有这个问题,他直接就过滤了非标的虚拟USB摄像头信息
(I found that FlashCap did not have this problem. It directly filtered the non-standard virtual USB camera information)
Hello,
I want to black out the camera. I had decent success with setting the brightness to the min value but this seems to be not working for every camera model. Can I apply a DirectShow Filter without "starting" the camera (I cannot start it if another application is already using it)? If so: What DirectShow filter should be used to make the camera stream go black?
Do you have any other suggestions?
Thanks in advance
Jannes
First Thankyou for this awesome work,
is there a way to use it with WPF?
Thank you for this sample and project. I have it working in Visual Studio 2022, but when I build it and take the executable andthe debug folder to another machine I get an immediate error: "Can't create filter" in usbCamera.
Any ideas on how to remedy this? What am I missing on the other Windows machine?
Thanks!
Don
First of all, thank you for this. This is realy great.
I'm trying to develop wpf app with this and i was testing with 3 different cameras (Logitech brio, one from lg and razer kiyo).
Lg and Razer are working fine with no problem, but i cant get it to work with brio and i dont know why.
I tried it with all possible video formats that i get from GetVideoFormat() method.
Problem appears here, when it tries to subscribe to event:
Message of exception here is: "Value does not fall within the expected range."
Any idea, what could be or can be done? If you need any more info, let me know. Thanks.
WPF 每次 BufferToBitmap 的时候都创建新的 WriteableBitmap 岂不是完全没发挥 WriteableBitmap 的性能
How to make the camera image size be the same size of the PictureBox?
Hi,
How i call/set preset from/to cam?
Example
tnx
Thanks for the neat library!
Tried running after compiling for x64 and it broke. Found a fix - you may want to replace line 320:
var dst = new IntPtr(bmp_data.Scan0.ToInt32() + (stride * y));
with
var dst = IntPtr.Add(bmp_data.Scan0, stride * y);
How can I set gain and exposure time?
We are experiencing a discrepancy in the image quality when saving Still capture from a monochrome sensor as an 8-bit BMP file. The output image does not match the expected quality and format, differing significantly from a reference BMP image known to be of high quality.
Hi, I am testing your code and I noticed that every time you take a snapshot the memory increases. Does it happen to you too?
Hello, when using an external video capture card, you may notice that the memory usage continues to increase, ultimately causing the program to crash. Is there a button for real-time release
How to improve the latency?
Hello @secile,
The Release is taking long time intermittently, I'm not sure why... tracking the call stack, it hangs on this line
case FILTER_STATE.Stopped: mediaControl.Stop(); break;
Any idea what could be the reason?
Steps to reproduce:
Tested with my laptop integrated camera
Hello,
I am currently working on a project involving two cameras. Initially, I was able to adjust exposure, brightness, and contrast during camera creation. However, when attempting to modify brightness or contrast dynamically at runtime using sliders or other methods, I encountered an exception, as shown in the attached screenshot. Interestingly, when I ran the cameras on the main thread, adjustments to brightness and contrast worked fine. However, my requirement is to run each camera on a separate thread. How can I ensure that I can adjust brightness and contrast when the cameras are running on different threads?
here is code to adjust brightness
`
public void SetExposure(int val)
{
try
{
UsbCamera.PropertyItems.Property prop;
prop = Camera_Device.Properties[DirectShow.CameraControlProperty.Exposure];
if (prop.Available)
{
if (val > prop.Max)
{
val = prop.Max;
}
else if (val < prop.Min)
{
val = prop.Min;
}
prop.SetValue(DirectShow.CameraControlFlags.Manual, val);
}
else
{
Console.WriteLine("Exposure is not there for camera :");
}
}catch(Exception ex)
{
Console.WriteLine("Exposure is not changing due to :" + ex.Message);
}
}
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.