• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
13
Question by Maisey · Aug 18, 2014 at 07:39 PM · cameraiosresolutionwebcamtextureratio

WebCamTexture, get correct resolution and RATIO.

After searc$$anonymous$$ng for a w$$anonymous$$le, I've seen different solutions to get t$$anonymous$$s right. Most of them suggesting first instantiating the WebCamTexture to a $$anonymous$$gh resoulution. T$$anonymous$$s does not work at all.

How do you, correctly, get the actual camera aspect ratio and the actual pixels??

Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Fattie · Jul 19, 2016 at 06:05 AM 0
Share

5 Replies

· Add your reply
  • Sort: 
avatar image
11
Best Answer

Answer by Fattie · Feb 29, 2016 at 12:16 AM

note

Thes days just use

NatCam

on the asset store. It saves 4-10 man-weeks of work.


Jonny Roy's answer is partially correct. T$$anonymous$$s is a huge know bug / disaster in Unity. For years they have not fixed, mentioned or addressed the issue.

(1) The solution is t$$anonymous$$s: the reported size only becomes correct after some time (1/2 sec or so).

(2) Before that the width is reported as a small number under 100. it sounds bizarre but you have to watch each frame for a number over 100. It works 100% reliably.

Note these days you would never use a WebCamTexture on anyt$$anonymous$$ng but UI, here is a post to save some typing: http://answers.unity3d.com/questions/909967/getting-a-web-cam-to-play-on-ui-texture-image.html

And nowm how to spin the image!

Here is the state of the art, 2016, for fixing the ratio, spin, and mirror of WebCamTexture. Works on both Android and iOS:

 private void Update()
   {
   if ( wct.width < 100 )
     {
     Debug.Log("Still waiting another frame for correct info...");
     return;
     }
   
   // change as user rotates iPhone or Android:
   
   int cwNeeded = wct.videoRotationAngle;
   // Unity helpfully returns the _clockwise_ twist needed
   // guess nobody at Unity noticed their product works in counterclockwise:
   int ccwNeeded = -cwNeeded;
   
   // IF the image needs to be mirrored, it seems that it
   // ALSO needs to be spun. Strange: but true.
   if ( wct.videoVerticallyMirrored ) ccwNeeded += 180;
   
   // you'll be using a UI RawImage, so simply spin the RectTransform
   rawImageRT.localEulerAngles = new Vector3(0f,0f,ccwNeeded);
   
   float videoRatio = (float)wct.width/(float)wct.height;
   
   // you'll be using an AspectRatioFitter on the Image, so simply set it
   rawImageARF.aspectRatio = videoRatio;
   
   // alert, the ONLY way to mirror a RAW image, is, the uvRect.
   // changing the scale is completely broken.
   if ( wct.videoVerticallyMirrored )
     rawImage.uvRect = new Rect(1,0,-1,1);  // means flip on vertical axis
   else
     rawImage.uvRect = new Rect(0,0,1,1);  // means no flip
   
   // devText.text =
   //  videoRotationAngle+"/"+ratio+"/"+wct.videoVerticallyMirrored;
   }


Hope it saves someone a LOT of time.

However see George's critical notes in the other answer!!!!!!!

Comment
Add comment · Show 10 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image georgehbr · Mar 14, 2016 at 03:01 PM 1
Share
avatar image Fattie · Mar 14, 2016 at 06:11 PM 0
Share
avatar image Guy-Corbett · Apr 24, 2016 at 08:43 PM 0
Share
avatar image sumit9236 · Jun 22, 2016 at 10:55 AM 0
Share
avatar image Olly · Jul 19, 2016 at 08:34 PM 0
Share
avatar image Lanre Olly · Jul 19, 2016 at 08:57 PM 0
Share
Show more comments
avatar image
23

Answer by georgehbr · Mar 15, 2016 at 01:31 PM

Update:

Here's the full script I'm using for displaying the device camera feed on a UI image with correct orientation and ratio, front and back cameras, and mirroring the front camera to make it look more natural, along with a screenshot of my $$anonymous$$erarchy and RawImage game object. It's based on t$$anonymous$$s answer by @Fattie, t$$anonymous$$s other answer by Max Bot, reading the Unity documentation on WebCamTexture and WebCamDevice, and trial and error on a Nexus 5 running Android 6 and an iPhone 5S running iOS 9.

Hierarchy:

alt text

DeviceCameraController.cs:

 using UnityEngine;
 using UnityEngine.UI;
 using System.Linq;
 using System.Collections;
 
 public class DeviceCameraController : MonoBehaviour
 {
     public RawImage image;
     public RectTransform imageParent;
     public AspectRatioFitter imageFitter;
 
     // Device cameras
     WebCamDevice frontCameraDevice;
     WebCamDevice backCameraDevice;
     WebCamDevice activeCameraDevice;
 
     WebCamTexture frontCameraTexture;
     WebCamTexture backCameraTexture;
     WebCamTexture activeCameraTexture;
 
     // Image rotation
     Vector3 rotationVector = new Vector3(0f, 0f, 0f);
 
     // Image uvRect
     Rect defaultRect = new Rect(0f, 0f, 1f, 1f);
     Rect fixedRect = new Rect(0f, 1f, 1f, -1f);
 
     // Image Parent's scale
     Vector3 defaultScale = new Vector3(1f, 1f, 1f);
     Vector3 fixedScale = new Vector3(-1f, 1f, 1f);
 
 
     void Start()
     {
         // Check for device cameras
         if (WebCamTexture.devices.Length == 0)
         {
             Debug.Log("No devices cameras found");
             return;
         }
 
         // Get the device's cameras and create WebCamTextures with them
         frontCameraDevice = WebCamTexture.devices.Last();
         backCameraDevice = WebCamTexture.devices.First();
 
         frontCameraTexture = new WebCamTexture(frontCameraDevice.name);
         backCameraTexture = new WebCamTexture(backCameraDevice.name);
 
         // Set camera filter modes for a smoother looking image
         frontCameraTexture.filterMode = FilterMode.Trilinear;
         backCameraTexture.filterMode = FilterMode.Trilinear;
 
         // Set the camera to use by default
         SetActiveCamera(frontCameraTexture);
     }
 
     // Set the device camera to use and start it
     public void SetActiveCamera(WebCamTexture cameraToUse)
     {
         if (activeCameraTexture != null)
         {
             activeCameraTexture.Stop();
         }
             
         activeCameraTexture = cameraToUse;
         activeCameraDevice = WebCamTexture.devices.FirstOrDefault(device => 
             device.name == cameraToUse.deviceName);
 
         image.texture = activeCameraTexture;
         image.material.mainTexture = activeCameraTexture;
 
         activeCameraTexture.Play();
     }
 
     // Switch between the device's front and back camera
     public void SwitchCamera()
     {
         SetActiveCamera(activeCameraTexture.Equals(frontCameraTexture) ? 
             backCameraTexture : frontCameraTexture);
     }
         
     // Make adjustments to image every frame to be safe, since Unity isn't 
     // guaranteed to report correct data as soon as device camera is started
     void Update()
     {
         // Skip making adjustment for incorrect camera data
         if (activeCameraTexture.width < 100)
         {
             Debug.Log("Still waiting another frame for correct info...");
             return;
         }
 
         // Rotate image to show correct orientation 
         rotationVector.z = -activeCameraTexture.videoRotationAngle;
         image.rectTransform.localEulerAngles = rotationVector;
 
         // Set AspectRatioFitter's ratio
         float videoRatio = 
             (float)activeCameraTexture.width / (float)activeCameraTexture.height;
         imageFitter.aspectRatio = videoRatio;
 
         // Unflip if vertically flipped
         image.uvRect = 
             activeCameraTexture.videoVerticallyMirrored ? fixedRect : defaultRect;
 
         // Mirror front-facing camera's image horizontally to look more natural
         imageParent.localScale = 
             activeCameraDevice.isFrontFacing ? fixedScale : defaultScale;
     }
 }


Comments on Fattie's Answer:

So I'm pretty sure at t$$anonymous$$s point that "verticallyMirrored" means that a rotation about the horizontal axis is needed. So I've modified the code in Fattie's answer to:

    int ccwNeeded = -wct.videoRotationAngle;
    
    rawImageRT.localEulerAngles = new Vector3(0f,0f,ccwNeeded);
    
    float videoRatio = (float)wct.width/(float)wct.height;
    
    rawImageARF.aspectRatio = videoRatio;
    
    if ( wct.videoVerticallyMirrored )
      rawImage.uvRect = new Rect(0,1,1,-1);  // flip on HORIZONTAL axis
    else
      rawImage.uvRect = new Rect(0,0,1,1); // no flip


i.e. I removed "if ( wct.videoVerticallyMirrored ) ccwNeeded += 180;" and changed the flipped uvRect values. I'll post a new answer here or somewhere on t$$anonymous$$s site with my full script once I iron it out w$$anonymous$$ch includes using both front and back cameras and mirroring the front camera's texture to make it more natural.


hierarchy.png (237.7 kB)
Comment
Add comment · Show 11 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Fattie · Mar 15, 2016 at 01:34 PM 0
Share
avatar image Fattie · Mar 15, 2016 at 01:34 PM 1
Share
avatar image drewwise · Jun 15, 2016 at 02:50 AM 0
Share
avatar image kuravista · Jul 19, 2016 at 04:52 AM 0
Share
myscreenshot-10-37-10-19-07-16.jpg (33.9 kB)
avatar image Fattie kuravista · Jul 19, 2016 at 06:03 AM 0
Share
avatar image Olly · Jul 19, 2016 at 08:41 PM 0
Share
Show more comments
avatar image
1

Answer by Lanre · Mar 17, 2016 at 06:01 PM

Have you tried NatCam? It works wonders and has a lot more features.

Comment
Add comment · Show 4 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Fattie · Mar 17, 2016 at 06:08 PM 0
Share
avatar image Lanre · Mar 17, 2016 at 06:16 PM 0
Share
avatar image Fattie Lanre · Mar 17, 2016 at 06:18 PM 0
Share
avatar image Lanre · Mar 17, 2016 at 06:17 PM 0
Share
avatar image
1

Answer by Zoophish · May 24, 2017 at 07:39 AM

Unity 5.6.1 Release Notes [Extract]:

  • Android: Fixed WebCamTexture crash with denied permissions. (877837)

  • Android: Webcam - Fixed the wrong orientation returned on first frames. (875247)

Hope t$$anonymous$$s solves a small issue faced here.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
1

Answer by highpockets · Nov 18, 2020 at 12:11 PM

Hey I was having good fun with t$$anonymous$$s on iOS, but I resolved it in the end with somet$$anonymous$$ng pretty short and sweet.


I still needed to wait for the WebCamTexture.width to be more than 100 before adding it to the raw image texture/material and then I used SetNativeSize() on the raw texture. Here is my code for initialization:

         private IEnumerator WaitForWebCamAndInitialize( WebCamTexture _webCamTexture ) 
         {
             w$$anonymous$$le( _webCamTexture.width < 100 )
                 yield return null;
 
             _isWebCamSet = true;
             _rawCamImage.texture = _webCamTexture;
             _rawCamImage.material.mainTexture = _webCamTexture;
             _rawCamImage.SetNativeSize();
 
             StartCoroutine( FadeToCameraView() );
         }

FadeToCameraView() does as it suggests.


I also had to rotate the rect transform negative 90 on the z axis because the app runs in portrait mode only and the raw data from the iOS camera seems to be aligned with landscape mode. Now everyt$$anonymous$$ng works like a charm on iOS, but testing on the iMac shows the image rotated by the negative 90 I gave it.


Hope that helps someone

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image ROBYER1 · Mar 22, 2022 at 02:48 PM 0
Share
avatar image Stevens-R-Miller · Mar 22, 2022 at 03:29 PM 0
Share

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

24 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

WebCamTexture, correct resolution and RATIO.And FPS 1 Answer

Orthographic Static 2D Background - IOS/Iphone 3,4 & 5 1 Answer

webcamtexture not able to set resolution 1 Answer

how to get 4:3 non cropped WebCamTexture in iOS 0 Answers

newbe scaling maze sceen for different resolutions 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges