我从Unity中的webcamtexture中获得纹理,但是对于我的项目来说太高了。
我不需要1280x720,但我会减小尺寸。
如何在Unity中更改参数?
谢谢你。谢谢你的指教。

最佳答案

webCamTexture.requestedWidth和webCamTexture.requestedHeight返回您最初尝试用来初始化WebCamTexture的宽度/高度。他们不会反射(reflect)真实的宽度/高度。同样,webCamTexture.width/webCamTexture.height也不总是如此。问题在于,由于设备摄像头的硬件和分辨率不同(通常与设备的屏幕不同),有时在某些情况下会在一段时间后确定webCamTexture的大小。

您可以做的是获取像素(webCamTexture.GetPixels())1次,然后在帧之后可以使用webCamTexture.width/.height返回捕获的纹理大小。

来自插件CameraCaptureKit(https://www.assetstore.unity3d.com/en/#!/content/56673)的此类代码示例,该代码具有执行您所描述的功能。

// ANDREAS added this: In some cases we apparently don't get correct width and height until we have tried to read pixels
    // from the buffer.
    void TryDummySnapshot( ) {
        if(!gotAspect) {
            if( webCamTexture.width>16 ) {
                if( Application.platform == RuntimePlatform.IPhonePlayer ) {
                    if(verbose)Debug.Log("Already got width height of WebCamTexture.");
                } else {
                    if(verbose)Debug.Log("Already got width height of WebCamTexture. - taking a snapshot no matter what.");
                    var tmpImg = new Texture2D( webCamTexture.width, webCamTexture.height, TextureFormat.RGB24, false );
                    Color32[] c = webCamTexture.GetPixels32();
                    tmpImg.SetPixels32(c);
                    tmpImg.Apply();
                    Texture2D.Destroy(tmpImg);
                }
                gotAspect = true;
            } else {
                if(verbose)Debug.Log ("Taking dummy snapshot");
                var tmpImg = new Texture2D( webCamTexture.width, webCamTexture.height, TextureFormat.RGB24, false );
                Color32[] c = webCamTexture.GetPixels32();
                tmpImg.SetPixels32(c);
                tmpImg.Apply();
                Texture2D.Destroy(tmpImg);
            }
        }
    }

回到问题的重点,当我遵循iOS代码时,应该可以通过将“requestedWidth/requstedHeight”设置为较小的值来设置较小的WebCamTexture纹理大小,然后Unity将(至少在iOS上)尝试并选择最接近您要求的纹理尺寸的相机分辨率。

这发生在CameraCapture.mm中
- (NSString*)pickPresetFromWidth:(int)w height:(int)h
{
static NSString* preset[] =
{
    AVCaptureSessionPreset352x288,
    AVCaptureSessionPreset640x480,
    AVCaptureSessionPreset1280x720,
    AVCaptureSessionPreset1920x1080,
};
static int presetW[] = { 352, 640, 1280, 1920 };

//[AVCamViewController setFlashMode:AVCaptureFlashModeAuto forDevice:[[self videoDeviceInput] device]];


#define countof(arr) sizeof(arr)/sizeof(arr[0])

static_assert(countof(presetW) == countof(preset), "preset and preset width arrrays have different elem count");

int ret = -1, curW = -10000;
for(int i = 0, n = countof(presetW) ; i < n ; ++i)
{
    if( ::abs(w - presetW[i]) < ::abs(w - curW) && [self.captureSession canSetSessionPreset:preset[i]] )
    {
        ret = i;
        curW = presetW[i];
    }
}

NSAssert(ret != -1, @"Cannot pick capture preset");
return ret != -1 ? preset[ret] : AVCaptureSessionPresetHigh;

#undef countof
 }

10-07 23:23