基于Directshow的USB视频捕获Delphi篇,二

参考:https://blog.csdn.net/dbyoung/article/details/78285942

使用回调方式,获取 USBCAMEAR 图像数据.

在类中添加 ISampleGrabberCB 接口

 TForm1 = class(TForm, ISampleGrabberCB)

ISampleGrabberCB 有两个回调方法,在 private 下添加声明:

function SampleCB(SampleTime: Double; pSample: IMediaSample): HResult; stdcall;

function BufferCB(SampleTime: Double; pBuffer: PByte; BufferLen: longint): HResult; stdcall;

SampleCB 中,将返回图像数据,这里的数据,有可能是YUV格式,也有可能是MJPG格式。根据你选择的视频格式不同而不同。

需要进行转化后显示。

在预览时,声明使用回调方式,不使用缓冲区方式。

FSampleGrabber.SetBufferSamples(False); // 不允许从 Buffer 中获取数据

FSampleGrabber.SetCallBack(Form1, 0); // 使用回调方式

这样就会触发上面的两个回调函数了。

{ 从回调中获取图像,应尽快处理,否则会影响 DirectShow 返回数据,此处代码应进行优化处理 }
function TForm1.SampleCB(SampleTime: Double; pSample: IMediaSample): HResult;
var
  BufferLen: Integer;
  ppBuffer : PByte;
  btTime   : Double;
begin
  Result := S_OK;
 
  BufferLen := pSample.GetSize;
  if BufferLen <= 0 then
    Exit;
 
  { 计算帧率 }
  Inc(FintCount);
  if FbakSampleTime = 0 then
  begin
    FbakSampleTime := SampleTime;
  end
  else
  begin
    btTime  := SampleTime - FbakSampleTime;
    Caption := Format('%d f/s', [Round(FintCount / btTime)]);
  end;
 
  { 获取图像 }
  pSample.GetPointer(ppBuffer);
  case FourCC of
    FourCC_YUY2, FourCC_YUYV, FourCC_YUNV: { YUV 数据格式 }
      begin
        YUY2_to_RGB(FBMP, ppBuffer);
        img1.Picture.Bitmap.Assign(FBMP);
      end;
    FourCC_MJPG: { JPEG 数据格式 }
      begin
        FMemStream.Clear;
        FMemStream.SetSize(BufferLen);
        FMemStream.Position := 0;
        FMemStream.WriteBuffer(ppBuffer^, BufferLen);
        FMemStream.Position := 0;
 
        if GDIPlusAvailable then
        begin
          GDIPlus_LoadBMPStream2(FMemStream, FBMP);
          img1.Picture.Bitmap.Assign(FBMP);
        end
        else
        begin
          FJPG.Grayscale := False;
          FJPG.LoadFromStream(FMemStream);
          FBMP.Width  := FJPG.Width;
          FBMP.Height := FJPG.Height;
          FBMP.Canvas.Draw(0, 0, FJPG);
          img1.Picture.Bitmap.Assign(FBMP);
        end;
      end;
  end;
end;

完整工程代码:http://download.csdn.net/download/dbyoung/10030158